Jquery UI的一个widgets
官网 :http://jqueryui.com/autocomplete/
- 首先要引入Jquery js 、Jquery UI 的css 和 js
- 配合ajax使用
$("#name").autocomplete({
source: function(request, response) {
$.ajax({
url: yourUrl",
dataType: "json",
type:"POST",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: {
"name": request.term
},
success: function(data) {
response($.map(data, function(item) {
return {
name: item.name,
code: item.code
}
}));
}
});
},
minLength: 1, //触发控件最小输入长度
autoFocus: true, //默认选中第一个元素
select: function(event, ui) {
$("#name").val(ui.item.name);
return false; //此段很重要,否则选中后input赋值会变空
}
}).autocomplete("instance")._renderItem = function(ul, item) {
return $("<li>").append("<div>" + item.name +"-"+item.code +"</div>").appendTo(ul);
};
<style type="text/css">
.ui-autocomplete {
max-height: 160px; //选择框高度
overflow-y: auto;
overflow-x: hidden; //溢出自动隐藏
}
/* IE 6 doesn't support max-height
* we use height instead, but this forces the menu to always be this tall
*/
* html .ui-autocomplete {
height: 100px;
}
</style>