我有一个带有自动完成功能的简单文本框,我已通过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但我想知道是否有更好的解决方案将name和id绑定在一起数据集并轻松获取所选的ID,而无需在每次选择新名称时循环遍历数据集。
答案 0 :(得分:1)
尝试
$("#prefetch .typeahead").typeahead(null, {
name: "customers",
displayKey: "name",
source: customers.ttAdapter()
}).on("typeahead:selected", function(event, suggestion, data) {
console.log(suggestion, suggestion.id);
});
请参阅<{p}}上的jQuery#typeahead - Custom Events
typeahead:selected
- 来自下拉列表的建议时触发 菜单已被选中。将使用3个参数调用事件处理程序: jQuery事件对象,建议对象,以及 建议所属的数据集。