1. 程式人生 > >input框 既可以手動輸入亦可以進行下拉模糊查詢

input框 既可以手動輸入亦可以進行下拉模糊查詢

實用情景:對資料進行篩選的時候,往往會碰到客戶要求輸入框既可以手動輸入進行實時模糊查詢也可以進行下拉選擇。

  1. 基本html:
<div class="organ-item">
     <span class="organ-itemt">相關單位:</span>
     <div class="nice-select" style="float:left;box-shadow:none">
        <input id="company_name" type="text" style="width:100%" class="organ-info cenz input"
placeholder="輸入相關單位"/>
<ul> <foreach name='company_arr' item='vo'> <li title='{$vo["name"]}'>{$vo.name}</li> </foreach> </ul> </div> </div>

2: js部分

// input 點選事件
$(document).on('click','.nice-select',function(e){
                $(".nice-select"
).find("ul").hide();// 讓ul隱藏(當你一個頁面多個這樣的輸入框時你就會用到) $(".nice-select ul li").show();// 列表展示 $(this).find('ul').show();// 當前子節點顯示 e.stopPropagation();// 阻止事件冒泡 })
// input 輸入事件
$(document).on('input','.input',function(){
        var keywords = $(this).val();
        var
count = 0; if (keywords != "") { $(".nice-select ul li").each(function(i) { var contentValue = $(this).text(); if(contentValue.toLowerCase().indexOf(keywords.toLowerCase()) < 0) { $(this).hide(); count++; } else { $(this).show(); } if (count == (i + 1)) { $(this).parent().find("ul").hide(); // $(".nice-select").find("ul").hide(); } else { $(this).parent().find("ul").show(); // $(".nice-select").find("ul").show(); } }); } else { $(".nice-select ul li").each(function(i) { $(this).show(); }); } }); // 點選頁面的任何一點讓input列表隱藏 $(document).click(function(){ $(".nice-select").find("ul").hide(); });

效果如下:這裡寫圖片描述

注:jQuery水平較差 還望多多指點!