我在这里看到了这篇文章:jQuery UI autocomplete with item and id但我无法弄清楚。
这是我输入的 html:
<input type="text" class="tags" style="width:250px; height:24px;"> </input>'
<input type="hidden" name="tags_id" id="tags_id" />
这是我的 ajax 调用:
var data = {};
$.get('/tags',data, function(tag_list) {
autocomplete_source_list = [];
for(var i = 0; i < tag_list.length; i++){
autocomplete_source_list.push([tag_list[i].fields.display_name, [2,3,4,5,6,7,8,9,1,2]]);
}
jQuery( ".tags" ).autocomplete({
source: autocomplete_source_list,
select: function (event, ui) {
$(".tags").val(ui.item.label); // display the selected text
$(".tags_id").val(ui.item.value); // save selected id to hidden input
console.log("selected id: ", ui.item.label)
}
});
});
如果将二维数组传递给源,如何设置 ids?当我将源指定为文本时, ui.item.value = ui.item.label =“无论文本”。我不明白如何附加 id。
请给我一些帮助。谢谢
最佳答案
来自fine manual :
The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu.
所以label
进入下拉菜单,然后显示 value
进入 <input type="text">
如果你想要一些不同的东西,你想要 <input type="text">
中的一件事和菜单和另一个东西在一个单独的<input type="hidden">
.
假设您从服务器返回了一些像这样的原始数据:
var raw = [
{ value: 1, label: 'one' },
{ value: 2, label: 'two' },
{ value: 3, label: 'three' },
{ value: 4, label: 'four' }
];
然后您可以构建一个数组和一个简单的映射对象:
var source = [ ];
var mapping = { };
for(var i = 0; i < raw.length; ++i) {
source.push(raw[i].label);
mapping[raw[i].label] = raw[i].value;
}
source
数组将被赋予 .autocomplete()
和你的select
处理程序将使用 mapping
找出要放入 <input type="hidden">
中的内容:
$('.tags').autocomplete({
source: source,
select: function(event, ui) {
$('.tags_id').val(mapping[ui.item.value]);
}
});
关于jquery - 如何让 JQuery UI 自动完成与项目 id 配合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9042090/