我正在尝试使用JQuery自动完成功能,但无法使其正常工作。当我从下拉列表中选择产品但搜索不起作用时,输入将获取值。不管我键入什么,每次都会显示2个选项。
<input style="width:80px;" id="product_code"></input>
<input style="width:220px;" id="product_name"></input>
--
var product = [
{
"name": "chocolate",
"code": "050"
},
{
"name": "cake",
"code": "10000"
}
];
$('#product_name').autocomplete({
minLength: 2,
source: function (request, response) {
response($.map(product, function (value, key) {
return {
label: value.name,
value: value.code
}
}));
},
select: function(event, ui) {
$('#product_code').val(ui.item.value);
$('#product_name').val(ui.item.label);
return false;
}
});
在source
jQuery的UI的自动完成的选项可以接受一个功能,你需要记住的是:
回调有两个参数:
request
具有单个term属性的对象,该对象引用文本输入中当前的值。例如,如果用户在城市字段中输入“ new yo”,则“自动完成”字词将等于“ new yo”。request.term
response
回调,需要一个参数:向用户建议的数据。该数据应根据提供的术语进行过滤,并且可以采用上述针对简单本地数据所述的任何格式。提供自定义源回调以处理请求期间的错误时,这一点很重要。即使遇到错误,也必须始终调用响应回调。这样可以确保小部件始终具有正确的状态。背后的想法source
是,它使您可以完全控制要显示的数据,但是,这也使您有责任进行所有过滤并决定要显示的值。
如果要检查数组中的name
或code
中的值product
是否具有您刚刚搜索的术语,则应使用:
if (val.name.indexOf(request.term) > -1 || val.code.indexOf(request.term) > -1)
这是一个例子:
var product = [
{
"name": "chocolate",
"code": "050"
},
{
"name": "cake",
"code": "10000"
}
];
$('#product_name').autocomplete({
minLength: 2,
source: function (request, response) {
response($.map(product, function (val, i) {
if (val.name.indexOf(request.term) > -1 || val.code.indexOf(request.term) > -1) {
return {
label: val.name,
value: val.code
};
}
}));
},
select: function(event, ui) {
$('#product_code').val(ui.item.value);
$('#product_name').val(ui.item.label);
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<input style="width:80px;" id="product_code"></input>
<input style="width:220px;" id="product_name"></input>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句