自动匹配的表单需要注意位置,在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);
});
|