我正在编写一段代码,该代码使用了jquery ui自动完成组件来过滤搜索到的项目。我必须配置它以便可以根据多个因子进行搜索,这是我的样本搜索数组:
var availableTags = [{
name: "Smith",
family: "Johnson",
account_number: "10032",
nick_name: "Friend account",
}, {
name: "Susan",
family: "Rice",
account_number: "343243",
nick_name: "Mom Account",
}, {
name: "Joe",
family: "Austin",
account_number: "3434",
nick_name: "Partner Account",
}, {
}];
自动完成应在显示建议框时显示姓名,家庭,帐号和nick_name。但是当选择每个项目时,只需将account_number插入文本框中。用户还必须能够搜索姓名,姓氏,帐号和昵称。我怎样才能达到这个目标?
答案 0 :(得分:1)
你需要:
value
参数(这允许自动完成在焦点/选择时填充输入)source
函数,根据用户键入的内容过滤数据_renderItem
函数,显示根据您的喜好格式化的数据所以你有:
var userData = [{
name: "Smith",
family: "Johnson",
value: "10032",
nick_name: "Friend account"
}, {
name: "Susan",
family: "Rice",
value: "343243",
nick_name: "Mom Account"
}, {
name: "Joe",
family: "Austin",
value: "3434",
nick_name: "Partner Account"
}];
$("#autocomplete").autocomplete({
source: function (request, response) {
var search = $.trim(request.term.toLowerCase());
var array = $.grep(userData, function (val) {
return
val.name.toLowerCase().indexOf(search) >= 0 ||
val.family.toLowerCase().indexOf(search) >= 0 ||
val.value.toLowerCase().indexOf(search) >= 0 ||
val.nick_name.toLowerCase().indexOf(search) >= 0;
});
response(array);
}
})
.data("ui-autocomplete")._renderItem = function (ul, item) {
var $a = $("<a></a>").text(item.name + " " + item.family);
$("<br />").appendTo($a);
$("<small></small>").text(item.nick_name).appendTo($a);
$("<br />").appendTo($a);
$("<small></small>").text(item.value).appendTo($a);
return $("<li></li>").append($a).appendTo(ul);
};