jquery - jQuery UI 自动完成:从对象数组加载:过滤被破坏
问题描述
我正在关注此线程中给出的 JSFiddle作为从简单的对象数组加载 jQuery UI AutoComplete 的解决方案:
过滤在这里被破坏了。有 2 个带有 First_Name 字符串的数据行,“Will”和“Willem”,但是如果您键入其他任何内容,例如“WA”,您仍然可以获得 2 个项目的完整选择,而应该没有。
var data = [
{
"id": 1,
"first_name": "Will",
"last_name": "Smith",
"created_at": "2015-01-27T13:09:20.243Z",
"updated_at": "2015-01-27T13:09:20.243Z"
},
{
"id": 2,
"first_name": "Willem",
"last_name": "Dafoe",
"created_at": "2015-01-27T13:17:23.479Z",
"updated_at": "2015-01-27T13:17:23.479Z"
}
];
$('#search').autocomplete({
// This shows the min length of charcters that must be typed before the autocomplete looks for a match.
minLength: 2,
source: function (request, response) {
response($.map(data, function (value, key) {
return {
label: value.first_name,
value: value.id
}
}));
},
focus: function(event, ui) {
$('#search').val(ui.item.first_name);
return false;
},
// Once a value in the drop down list is selected, do the following:
select: function(event, ui) {
// place the person.given_name value into the textfield called 'select_origin'...
$('#search').val(ui.item.first_name);
// and place the person.id into the hidden textfield called 'link_origin_id'.
$('#link_origin_id').val(ui.item.id);
return false;
}
解决方案
考虑以下代码示例source
:
source: function(request, response) {
var results;
var aData = $.map(data, function(value, key) {
return {
label: value.first_name,
value: value.id
}
});
results = $.ui.autocomplete.filter(aData, request.term);
response(results);
}
首先,我们将您的数据映射到{ label, value }
Autocomplete 所期望的对。然后,我们使用$.ui.autocomplete.filter()
像 Autocomplete 一样执行预期的过滤。这为我们提供了我们可以发送response()
到显示的结果数组。
工作示例:https ://jsfiddle.net/Twisty/svnbw2uj/3/
希望有帮助。
推荐阅读
- regex - 需要正则表达式查找和替换以忽略字符串中的代码字符
- sas-macro - 在 SAS 中使用宏生成联合语句
- python - 如何在python中按日期时间对列表进行排序?
- postgresql - 无法启动 docker 容器,“docker ps -a” STATUS = Exited (1)
- php - 如何使用或不使用插件将实时 wordpress 站点迁移到我的本地主机
- angular - 尝试即时更新生成的 angular6-json-schema-form
- javascript - 找不到带有 rails 5 和 es6 的 babel-transpiler?
- mysql - SQL 替换所有指定的键
- java - 使用 java Collections 出乎意料
- r - 如何为 R 中的预测创建坐标网格