如何在JQuery UI自动完成中搜索多个属性?
问题描述:
我有对象的数组类似这样的结构:如何在JQuery UI自动完成中搜索多个属性?
$scope.usersList = [{
"name": "John",
"email": "[email protected]",
"id": "abcd"
},{
"name": "Jane",
"email": "[email protected]",
"id": "efgh"
}];
我调用Ajax到服务器后,即可获取阵列。我目前使用jQuery UI自动完成在角应用这样
$(input).autocomplete({
source: $scope.usersList,
appendTo: container,
position: {
at: 'left bottom',
of: container
},
select: function(e, v) {
e.preventDefault();
//Do something
}
});
如果阵列只包含名字,上面的代码工作,但我希望跨“电子邮件”和“ID”字段进行搜索,以及。例如如果我在搜索框中输入“abcd”,我想在结果列表中看到John的名字。我无法弄清楚如何处理这个问题。
答
能不能请你修改源如下:
$("#suggest").autocomplete({
delay: 100,
minLength:2,
**source: function (request, response) {
var temp = [];
usersList.filter(buildResponse);
function buildResponse(p){
for (var key in p) {
if (p.hasOwnProperty(key)) {
if(p[key].indexOf(request.term) > -1){
temp.push({
"label" : p[key],
"value" : p
});
}
}
}
}
console.log(temp);
response(temp);
}**,
select: function (event, ui) {
// Prevent value from being put in the input:
this.value = ui.item.label;
// Set the next input's value to the "value" of the item.
console.log(ui.item);
event.preventDefault();
}
});
// usersList = $ scope.usersList(在你的问题中提到)
的jsfiddle:http://jsfiddle.net/32Bck/501/
答
过了一会绊脚石,我设法让搜索词成为任何财产。这应该在你的情况下工作(刚刚替补var usersList
您的藏品):
<input id="in" type="input" class="ui-autocomplete-input" />
var usersList = [{
"name": "John",
"email": "[email protected]",
"id": "abcd"
}, {
"name": "Jane",
"email": "[email protected]",
"id": "efgh"
}];
$("#in").autocomplete({
source: function(request, response) {
function hasMatch(s) {
return s.toLowerCase().indexOf(request.term.toLowerCase()) !== -1;
}
var i, l, obj, matches = [];
if (request.term === "") {
response([]);
return;
}
for (i = 0, l = usersList.length; i < l; i++) {
obj = usersList[i];
if (hasMatch(obj.name) || hasMatch(obj.email) || hasMatch(obj.id)) {
if ($.inArray(obj, matches) < 1) { // remove duplicates
matches.push({
"label": obj.name
//add here other properties you might need
})
}
}
response(matches);
}
}
});
在这里工作小提琴:https://jsfiddle.net/qg50zwv3/
实现'source'为使用任何你需要的过滤器的逻辑功能。 http://api.jqueryui.com/autocomplete/#option-source –
如果能解决您的问题,您能否接受答案? – Nitesh