jquery+bigAutocomplete+PHP 自动补全
先看效果图
- 将bigautocomplete加载进来
<script src="/static/admin/js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="/static/admin/js/input-autocomplete.js" type="text/javascript"></script>
- html代码
<div class="layui-input-4">
<input id="param" class="layui-input" autocomplete="off"/>
<input id="custid" name="custid" type="hidden" />
</div>
- javascript代码:
$("#param").bigAutocomplete({
// data: data3,
url: "{:url('search')}", //后台接口
title:'text',
formatItem:function(data, i, row){
return row.name + ' ' + row.telphone + ' (' +row.company + ')';
},
formatSelected:function(data, i, row){
return row.name + ' ' + row.telphone + ' (' +row.company + ')';
},
callback:function(row,param){
$("#custid").val(row.id);
// console.log(data)
// console.log('param:'+ param + 'value:' + row.value);
},
param:1,
});
- 服务端返回数据格式:
{
"data":[{
"id":1,"name":"李晓华","company":"北京的测试公司","telphone":"18234876545"},{
"id":2,"name":"夏华","company":"暂无","telphone":"18765456666"},{
"id":3,"name":"user123","company":"user123的测试公司","telphone":"18398909876"}
- 服务端的代码:(以ThinkPHP示例)
public function search(){
$keywords = $_POST['keyword'];
$customer['data'] = db('customer')->where('name|company|telphone','like',"%".$keywords."%")->field('id,name,company,telphone')->select ();
foreach ($customer['data'] as $key => $value) {
if (!$value['company'] || $value['company'] == null) {
$customer['data'][$key]['company'] = '暂无';
}
}
echo json_encode($customer,JSON_UNESCAPED_UNICODE);
}
默认是POST过来的数据,名称是keyword,返回数据是和本地data一致的。
jquery.bigautocomplete.js
/*!
input-autocomplete v1.0
@author: starIl
*/
(function($){
var bigAutocomplete = new function(){
this.currentInputText = null;//目前获得光标的输入框(解决一个页面多个输入框绑定自动补全功能)
this.functionalKeyArray = [9,20,13,16,17,18,91,92,93,45,36,33,34,35,37,39,112,113,114,115,116,117,118,119,120,121,122,123,144,19,145,40,38,27];//键盘上功能键键值数组
this.holdText = null;//输入框中原始输入的内容
//初始化插入自动补全div,并在document注册mousedown,点击非div区域隐藏div
this.init = function(){
$("body").append("<div id='bigAutocompleteContent' class='bigautocomplete-layout'></div>");
$(document).bind('mousedown',function(event){
var $target = $(event.target)