一、添加CSS和JS引用javascript
<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>
二、在某些使用DIV並設置了z-index的頁面裏使用可能須要重寫css的內容css
<style type="text/css"> .ui-autocomplete{ display:block; z-index:99999; width: 200px; } </style>
三、頁面初始化後綁定事件java
1 $( "#vip_code" ).autocomplete({ 2 source: function(request, response){ 3 $.ajax({ 4 type : "POST", 5 url :"<%=basePath%>" + "/xfz/customer.do", 6 data : "action=autoSearch&key="+$("#vip_code").val(), 7 dataType : "json", 8 success : function(jsonObj) { 9 response(jsonObj); 10 } 11 }); 12 }, 13 minLength:2, //至少得有2個字符才能觸發自動匹配的動做 14 select: function( event, ui ) { 15 $("#customer_name").val(ui.item.name); 16 } 17 }) 18 .data( "ui-autocomplete" )._renderItem = function( ul, item ) { 19 return $( "<li>" ) 20 .append( "<a style='font-size:12px;font-family: 微軟雅黑;'>" + item.value + "," + item.name + "," + item.mobilephone + "</a>" ) 21 .appendTo( ul ); 22 };
後臺返回給前臺的是一個以下結構的對象listjquery
1 public class CustomerAutoInfo { 2 //value is key value(vipcode/username) 3 private String value; 4 private String name; 5 private String mobilephone; 6 7 public String getValue() { 8 return value; 9 } 10 public void setValue(String value) { 11 this.value = value; 12 } 13 public String getName() { 14 return name; 15 } 16 public void setName(String name) { 17 this.name = name; 18 } 19 public String getMobilephone() { 20 return mobilephone; 21 } 22 public void setMobilephone(String mobilephone) { 23 this.mobilephone = mobilephone; 24 } 25 }
4.HTML代碼ajax
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。json
更多詳細的用法請參考Jquery-ui的官方文檔app