使用 twitter typeahead JQuery 插件从 json 文件获取 id
Get the id from json file with twiiter typehead JQuery plugin
我有一个带有自动完成功能的简单文本框,我通过 this plugin 设法实现了它。
一切正常,但我想从 json 文件中检索与所选项目相关的 ID,以便能够对数据库执行更新。
json 对象如下所示:
[{"id":1,"name":"John Smith"},{"id":2,"name":"Mary Brown"},{"id":3,"name":"Joe April"}]
Here's a working example 没有 ID 检索功能,这正是我想要弄清楚的。
我知道我可以获得选定的名称并通过 json 对象循环执行新的搜索以匹配字符串并获取 ID,但我想知道是否有更好的解决方案来绑定两个名称和 id 一起作为一个数据集,并轻松获得所选的 id,而无需在每次选择新名称时循环遍历数据集。
尝试
$("#prefetch .typeahead").typeahead(null, {
name: "customers",
displayKey: "name",
source: customers.ttAdapter()
}).on("typeahead:selected", function(event, suggestion, data) {
console.log(suggestion, suggestion.id);
});
参见jQuery#typeahead - Custom Events
typeahead:selected
– Triggered when a suggestion from the dropdown
menu is selected. The event handler will be invoked with 3 arguments:
the jQuery event object, the suggestion object, and the name of the
dataset the suggestion belongs to.
我有一个带有自动完成功能的简单文本框,我通过 this plugin 设法实现了它。 一切正常,但我想从 json 文件中检索与所选项目相关的 ID,以便能够对数据库执行更新。
json 对象如下所示:
[{"id":1,"name":"John Smith"},{"id":2,"name":"Mary Brown"},{"id":3,"name":"Joe April"}]
Here's a working example 没有 ID 检索功能,这正是我想要弄清楚的。
我知道我可以获得选定的名称并通过 json 对象循环执行新的搜索以匹配字符串并获取 ID,但我想知道是否有更好的解决方案来绑定两个名称和 id 一起作为一个数据集,并轻松获得所选的 id,而无需在每次选择新名称时循环遍历数据集。
尝试
$("#prefetch .typeahead").typeahead(null, {
name: "customers",
displayKey: "name",
source: customers.ttAdapter()
}).on("typeahead:selected", function(event, suggestion, data) {
console.log(suggestion, suggestion.id);
});
参见jQuery#typeahead - Custom Events
typeahead:selected
– Triggered when a suggestion from the dropdown menu is selected. The event handler will be invoked with 3 arguments: the jQuery event object, the suggestion object, and the name of the dataset the suggestion belongs to.