layui select配合input實現動態模糊搜索

功能需求:select框能夠本身輸入,就是在下拉列表裏找不到本身想要的選項就能夠本身輸入,同時還要支持模糊匹配功能css


html代碼:html

樣式:ui

1 <style>
2  .select-search-input {
3  position: absolute;
4  z-index: 2;
5  width: 80%;
6     }
7 </style>

 

select部分:spa

 1 <div class="layui-form-item layui-inline">
 2     <label class="layui-form-label" style="width:60px;">用戶列表</label>
 3     <div class="layui-input-inline" style="width:150px;">
 4         <input type="text" name="selectInputUser" id="selectInputUser" class="layui-input select-search-input" value="" onkeyup="search();" autocomplete="off">
 5         <select name="user_id" id="selectUser" lay-filter="selectUser" autocomplete="off" class="layui-select" lay-search>
 6             <option value="">-不限-</option>
 7             <option value="1">張三</option>
 8             <option value="2">李四</option>
 9             <option value="3">王二麻子</option>
10         </select>
11     </div>
12 </div>

其中input的幾個style樣式簡單說一下:
position:absolute:在這裏是讓input和select在同一位置。
z-index:2 是爲了讓input在select上面。
width:80% 是爲了避免蓋住select後面的小三角符號,select還能夠點擊。
autocomplete="off" 爲了避免自動填充input框,省得壓蓋select選項code

 

JS代碼:orm

 

 1 layui.use(['form', 'layedit','upload'], function () {  2     var form = layui.form  3     form.on('select(selectUser)', function (data) {   //選擇並賦值給input框
 4         // value:data.value
 5         // 文本:data.elem[data.elem.selectedIndex].text;
 6         var txt = data.elem[data.elem.selectedIndex].text;  7         $("#selectInputUser").val(txt);  8         $("#selectUser").next().find("dl").css({ "display": "none" });  9  form.render(); 10  }); 11 
12     window.search = function () { 13         var value = $("#selectInputUser").val(); 14         $("#selectUser").val(value); 15  form.render(); 16         $("#selectUser").next().find("dl").css({ "display": "block" }); 17         var dl = $("#selectUser").next().find("dl").children(); 18         var j = -1; 19         for (var i = 0; i < dl.length; i++) { 20             if (dl[i].innerHTML.indexOf(value) <= -1) { 21                 dl[i].style.display = "none"; 22                 j++; 23  } 24             if (j == dl.length-1) { 25                 $("#selectUser").next().find("dl").css({ "display": "none" }); 26  } 27  } 28  } 29 });

done!htm

相關文章
相關標籤/搜索