总结下运用jquery的autocomplete的基本用法(自动联想填充)。
1.引入基本的jquery的包。
2.HTML 文件
<input type="text" id="Aorg_name" class="form-control" >
<input type="hidden" id="Aorg_code">
隐藏的input用于放对应的ID。
3.js文件
用ajax取得你需要的data。(假如一下子取到了)
var retData = data;
AutoCompleteForOrg(retData,$("#Aorg_name"),$("#Aorg_code"));
AutoCompleteForOrg()的方法:
function AutoCompleteForOrg(data,ele_name,ele_id) {
$(ele_name).autocomplete({
minLength: 0,
source: function (req, res) {
var term = req.term.trim();
var matcher = new RegExp($.ui.autocomplete.escapeRegex(term), "i");
res($.map(data, function (el) {
/* Remove dashes from the source and compare with the term: */
if (matcher.test(el.dep_name || matcher.test(el.dep_id))) {
return el;
}
}));
},
minChars: 0,
max: 5,
autoFill: true,
mustMatch: true,
matchContains: true,
scrollHeight: 60,
open: function (event, ui) {
$('.ui-autocomplete').css('position', 'absolute');
},
focus: function (event, ui) {
$(ele_name).attr('source', ui.item.source);
return false;
},
select: function (event, ui) {
$(ele_name).val(ui.item.dep_name);
$(ele_id).val(ui.item.dep_id)
return false;
}
})
.data( "ui-autocomplete" )._renderItem = function(ul,item) {
return $( "<li style='list-style:none;'>" )
.append( "<a>" + item.dep_name + "</a>" )
.appendTo(ul);
};
}
4.好了,大功告成: