bootstrap的插件 autocomplete

自动匹配的表单需要注意位置,在css上调整

基于bootstrap插件实现autocomplete自动完成表单,提供脚本代码,用例,以及后台服务端(php),

Bootstrap自动完成控件Autocomplete是基于bootstrap自带控件typeahead改造而来,因为 typeahead不支持复杂的对象。

据说最新版本的typehead控件中sourse里不支持ajax直接调用?

首先肯定还是加载bootstrap&jquery了,注意声明顺序。需要额外说明的是,后端返回的二维数组,和formatItem方法下面的调用保持一致即可;
另外,返回的数据要先parseJSON!切记。

相关参数说明:

source:function(query,process){}。query表示当前文本输入框中的字符串,可在该方法中通过ajax向后台请求数据(数组形式的json对象),然后将返回的对象作为process的参数;
formatItem:function(item){}。对返回数据的具体某个json对象转化为字符串格式,用以显示在提示列表中,返回值:字符串;
setValue:function(item){}。选中提示列表某项时,设置文本输入框中显示的值以及实际需要获取的值。返回值格式:{'data-value':item["输入框显示值的item属性"],'real-value':item["实际需要获取值的item属性"]},后期可通过文本输入框的real-value属性获取该值;
items:自动完成提示的最大结果集数量,默认:8;
minLength:当前文本输入框中字符串达到该属性值时才进行匹配处理,默认:1;
delay:指定延时毫秒数后,才正真向后台请求数据,以防止输入过快导致频繁向后台请求,默认:500

基于bootstrap插件实现autocomplete自动完成表单,代码如下

1.代码


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<script>
$( '#sim_iccid' ).autocomplete({
  source: function (query,process){
  var matchCount = this .options.items; //允许返回结果集最大数量
  $.get( "http://www.soyiyuan.com/update/" ,{ "iccid" :query, "matchCount" :matchCount}, function (respData){
   respData = $.parseJSON(respData); //解析返回的数据
   return process(respData);
  });
  },
  formatItem: function (item){
  return item[ "iccid" ]+ "(" +item[ "mobile" ]+ ")" ;
  },
  setValue: function (item){
  return { 'data-value' :item[ "iccid" ], 'real-value' :item[ "mobile" ]};
  }
});
</script>

2. $data为一个二维数组    
echo json_encode( $data )
3. 需要返回的标准json格式    

[code][{"iccid":"12345678901234567890","mobile":"1850000"},{"iccid":"12345785","mobile":"1850001"}][code]



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//示例代码如下:
  
$( '#autocompleteInput' ).autocomplete({
  source: function (query,process){
   var matchCount = this .options.items; //返回结果集最大数量
   $.post( "/bootstrap/region" ,{ "matchInfo" :query, "matchCount" :matchCount}, function (respData){
   return process(respData);
   });
  },
  formatItem: function (item){
   return item[ "regionName" ]+ "(" +item[ "regionNameEn" ]+ "," +item[ "regionShortnameEn" ]+ ") - " +item[ "regionCode" ];
  },
  setValue: function (item){
   return { 'data-value' :item[ "regionName" ], 'real-value' :item[ "regionCode" ]};
  }
  });
  
$( "#goBtn" ).click( function (){ //获取文本框的实际值
  var regionCode = $( "#autocompleteInput" ).attr( "real-value" ) || "" ;
  alert(regionCode);
  });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值