jquery - 如何让 JQuery UI 自动完成与项目 id 配合使用

标签 jquery jquery-ui jquery-ui-autocomplete

我在这里看到了这篇文章: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]);
    }
});

演示:http://jsfiddle.net/ambiguous/GVPPy/

关于jquery - 如何让 JQuery UI 自动完成与项目 id 配合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9042090/

相关文章:

javascript - jQuery:加载txt文件并插入div

javascript - Knockout.js - 在通过可观察对象设置值时防止更改事件绑定(bind)触发

javascript - jQuery fadeTo() 用于颜色

javascript - 没有js的自定义微调器输入类型号

jQuery UI 可排序/可拖动嵌套示例

jquery-ui - JQuery UI 自动完成语法

Jquery 自动完成返回结果,但结果没有显示任何内容

javascript - 如何在延迟后显示建议而不使用 jquery UI 自动完成按任何键?

JQuery ui selectmenu 占位符不起作用

javascript - jQueryUI 对话框错误?