1、添加CSS和JS引用
<script type="text/javascript" src="javascript/jquery-1.7.min.js"></script>
<link rel="stylesheet" href="javascript/menuui/jquery-ui.css" >
<script src="javascript/autocomplete/jquery.ui.core.js"></script>
<script src="javascript/autocomplete/jquery.ui.widget.js"></script>
<script src="javascript/autocomplete/jquery.ui.position.js"></script>
<script src="javascript/autocomplete/jquery.ui.menu.js"></script>
<script src="javascript/autocomplete/jquery.ui.autocomplete.js"></script>
2、在某些使用DIV并设置了z-index的页面里使用可能需要重写css的内容
<style type="text/css">
.ui-autocomplete{
display:block;
z-index:;
width: 200px;
}
</style>
3、页面初始化后绑定事件
$( "#vip_code" ).autocomplete({
source: function(request, response){
$.ajax({
type : "POST",
url :"<%=basePath%>" + "/xfz/customer.do",
data : "action=autoSearch&key="+$("#vip_code").val(),
dataType : "json",
success : function(jsonObj) {
response(jsonObj);
}
});
},
minLength:2, //至少得有2个字符才能触发自动匹配的动作
select: function( event, ui ) {
$("#customer_name").val(ui.item.name);
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a style='font-size:12px;font-family: 微软雅黑;'>" + item.value + "," + item.name + "," + item.mobilephone + "</a>" )
.appendTo( ul );
};
后台返回给前台的是一个如下结构的对象list
public class CustomerAutoInfo {
//value is key value(vipcode/username)
private String value;
private String name;
private String mobilephone; public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobilephone() {
return mobilephone;
}
public void setMobilephone(String mobilephone) {
this.mobilephone = mobilephone;
}
}
4.HTML代码
VIP信息员编码 <input type="text" id="vip_code" onkeydown='return checkNum()' style="ime-mode:Disabled" onpaste="return !clipboardData.getData('text').match(/\D\./)" ondragenter="return false" class="searchinput" /> <label for="customer_name" style="width: 100px;text-align: right;">消费者姓名</label><input type="text" id="customer_name" onkeydown="if(event.keyCode==32) return false" class="searchinput" />
达到的结果是在VIP信息员编码上输入超过2个数字后提示与之匹配的信息员的 编码,名字,电话号码 信息提示框 供选择,选择完成后自动填充名字的input。
更多详细的用法请参考Jquery-ui的官方文档