$("#search").autocomplete({
minLength: 0,
source: function(request,response){
// request对象只有一个term属性,对应用户输入的文本
// response是一个函数,在你自行处理并获取数据后,将JSON数据交给该函数处理,以便于autocomplete根据数据显示列表
var dataObj = kwplan._getjsondata(request);
response(dataObj);
},
focus :function () {
return false;
},
select: function(event, ui){
$this = $(this);
// 这里的this指向当前输入框的DOM元素
// event参数是事件对象
// ui对象只有一个item属性,对应数据源中被选中的对象
var event = event||window.event;
this.value = ui.item.label;
$("#teacherid").val(ui.item.category);
// 必须阻止事件的默认行为,否则autocomplete默认会把ui.item.value设为输入框的value值
event.preventDefault();
setTimeout(function () {
$this.blur();
}, 1);
}
}).focus(function(){
$(this).autocomplete("search");
return false;
}
);
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Categories</title>
<link rel="stylesheet" href="../../themes/base/jquery.ui.all.css">
<script src="../../jquery-1.9.1.js"></script>
<script src="../../ui/jquery.ui.core.js"></script>
<script src="../../ui/jquery.ui.widget.js"></script>
<script src="../../ui/jquery.ui.position.js"></script>
<script src="../../ui/jquery.ui.menu.js"></script>
<script src="../../ui/jquery.ui.autocomplete.js"></script>
<link rel="stylesheet" href="../demos.css">
<style>
.ui-autocomplete-category {
font-weight: bold;
padding: .2em .4em;
margin: .8em 0 .2em;
line-height: 1.5;
}
</style>
<script>
var data = [
{ label: "anders", category: "" },
{ label: "andreas", category: "" },
{ label: "antal", category: "" },
{ label: "annhhx10", category: "Products" },
{ label: "annk K12", category: "Products" },
{ label: "annttop C13", category: "Products" },
{ label: "anders andersson", category: "People" },
{ label: "andreas andersson", category: "People" },
{ label: "andreas johnson", category: "People" }
];
function dynamicAutocomplete(){
$("#search").autocomplete({
minLength: 0,
source: data,
focus :function () {
return false;
},
select: function(event, ui){
$this = $(this);
setTimeout(function () {
$this.blur();
}, 1);
}
}).focus(function(){
$(this).autocomplete("search");
return false;
}
);
};
</script>
</head>
<body>
<button onclick="dynamicAutocomplete()">autocomplete</button> <br />
<label for="search">Search: </label>
<input id="search">
<div class="demo-description">
<p>A categorized search result. Try typing "a" or "n".</p>
</div>
</body>
</html>