Jquery autocomplete.js输入框联想补全功能
Jquery autocomplete.js插件下载地址:https://files.cnblogs.com/files/jinzhiming/autocomplete.rar
有两种用法,一种是直接使用页面的数据,一种是输入请求地址,请求后台返回数据
1.数据格式就是下方这种
<link href="../autocomplete/jquery.autocomplete.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="../lib/jQuery-1.4.4.min.js"></script> <script type="text/javascript" src="../autocomplete/jquery.autocomplete.js"></script> <input type="text" value="" id="searchInput" /> <script> var emails = [ { name: "Peter Pan", to: "peter@pan.de" }, { name: "Molly", to: "molly@yahoo.com" }, { name: "Forneria Marconi", to: "live@japan.jp" }, { name: "Master <em>Sync</em>", to: "205bw@samsung.com" }, { name: "Dr. <strong>Tech</strong> de Log", to: "g15@logitech.com" }, { name: "Don Corleone", to: "don@vegas.com" }, { name: "Mc Chick", to: "info@donalds.org" }, { name: "Donnie Darko", to: "dd@timeshift.info" }, { name: "Quake The Net", to: "webmaster@quakenet.org" }, { name: "Dr. Write", to: "write@writable.com" }, { name: "GG Bond", to: "Bond@qq.com" }, { name: "Zhuzhu Xia", to: "zhuzhu@qq.com" } ]; $(function(){ $("#searchInput").autocomplete(emails, { max: 5, //列表里的条目数 minChars: 0, //自动完成激活之前填入的最小字符 width: $("#searchInput").width()+1, //提示的宽度,溢出隐藏 scrollHeight: 300, //提示的高度,溢出显示滚动条 matchContains: true, //包含匹配,就是data参数里的数据,是否只要包含文本框里的数据就显示 autoFill: false, //自动填充 formatItem: function(row, i, max) { return i + '/' + max + ':"' + row.name + '"[' + row.to + ']'; }, formatMatch: function(row, i, max) { return row.name + row.to; }, formatResult: function(row) { return row.to; } }).result(function(event, row, formatted) { alert($("#searchInput").width()); }); }); </script>
2.后台传过来的数据格式也可以是上边这种,但是需要重写下parse方法:
[{"bankCode":"111","bankName":"中国工商银行"},{"bankCode":"2","bankName":"中国银行"}]
$(function(){ $("#inbankid").autocomplete('<%=request.getContextPath() %>/protected/accountAction.do?m=searchBankName', { max: 5, //列表里的条目数 minChars: 1, //自动完成激活之前填入的最小字符 width: $("#inbankid").width(), //提示的宽度,溢出隐藏 scrollHeight: 300, //提示的高度,溢出显示滚动条 matchContains: true, //包含匹配,就是data参数里的数据,是否只要包含文本框里的数据就显示 autoFill: false, //自动填充 dataType : "json", parse: function(data){ var rows = []; var d = data; for(var i=0; i<d.length; i++){ rows[rows.length] = { data:d[i], value:d[i].bankName, result:d[i].bankName }; } return rows; }, formatItem: function(row, i, max) { return row.bankName + '[' + row.bankCode + ']'; }, formatMatch: function(row, i, max) { return row.bankName; }, formatResult: function(row) { return row.bankName; } }).result(function(event, row, formatted) { }); });