select实现输入模糊匹配与选择双重功能

时间:2021-12-14 05:03:21

下载jqueryUI插件

引入

<link rel="stylesheet" type="text/css" href="/js/jquery/plugins/jqueryUI/jquery-ui.min.css">

<script src='/js/jquery/plugins/jqueryUI/jquery-ui.min.js'></script>

html代码

               <div class="navbar-form navbar-left" role="search" id="schoolConfig">
<span class='form-group-addon' style="font-size:16px;">选择学校:</span>
<div class="form-group" id="schoolQuery" style="position:relative;">
<span style="margin-left:100px;width:18px;overflow:hidden;">
<select id="schoolId" style="width:118px;margin-left:-100px" onchange="setValue(this)"></select>
</span>
<input id="schoolName" class="form-control" placeholder="学校名称" style="width:100px;position:absolute;left:0px;top:0px;height:30px;" onblur="reLoadSection()">
</div>
</div>

js代码

 /**
* 将select的值放入input框
*/
function setValue(obj){
var index = obj.selectedIndex; // 选中索引
var value = obj.options[index].value; // 选中值
var schoolName = obj.options[index].text; // 选中文本
$('#schoolName').val(schoolName); }
  $.getJSON(//获取学校数据
'/test/manage/user/school_findAllName.action',
function(data){
$( "#schoolName" ).autocomplete({
source: data
});
}
);
initCombo($('#schoolId'),'/test/manage/user/school_findAllIdAndSchoolName.action','schoolId','schoolName'); 返回数据格式为数组 eg:
["西科大","川大","电子科技大学","川音","北大","清华","复旦","上海交大 ","北邮","西石油"]
 /**
* init combobox
* @return {}
*/
function initCombo(combo,url,valueField,displayField){
$.getJSON(
url,
function(data){
if(data.rows && data.rows.length>0){
var html = '<option></option>',
rows = data.rows,
len = rows.length; for(var i=0; i<len; i++)
html += "<option value='"+ rows[i][valueField] + "'>"+ rows[i][displayField] +"</option>";
combo.html(html);
}
}
);
}

extend:可输入的select功能可以通过h5的list属性(datalist)实现。