在twitter bootstrap Typeahead处理选定的事件?

我想在用户使用twitter bootstrap Typeahead 选择一个值后运行javascript函数

我搜索一些像选定的事件

$('.typeahead').on('typeahead:selected', function(evt, item) { // do what you want with the item here }) 
 $('.typeahead').typeahead({ updater: function(item) { // do what you want with the item here return item; } }) 

我第一次在这里发布了答案(很多时候我在这里找到了答案),所以这是我的贡献,希望它有所帮助。 你应该能够检测到一个变化 – 试试这个:

 function bob(result) { alert('hi bob, you typed: '+ result); } $('#myTypeAhead').change(function(){ var result = $(this).val() //call your function here bob(result); }); 

有关typeahead在此处执行操作的方式的说明,请使用以下代码示例:

HTML输入字段:

  

JavaScript代码块:

 $('#my-input-field').typeahead({ source: function (query, process) { return $.get('json-page.json', { query: query }, function (data) { return process(data.options); }); }, updater: function(item) { myOwnFunction(item); var $fld = $('#my-input-field'); return item; } }) 

说明:

  1. 您的输入字段设置为具有第一行的预先输入字段: $('#my-input-field').typeahead(
  2. 输入文本时,它会触发source:选项以获取JSON列表并将其显示给用户。
  3. 如果用户单击某个项目(或使用光标键选择并输入),则会运行updater:选项。 请注意,它尚未使用所选值更新文本字段
  4. 您可以使用item变量获取所选项目并使用它执行所需操作,例如myOwnFunction(item)
  5. 我已经包含了一个创建对输入字段本身$fld的引用的示例,以防您想要对它执行某些操作。 请注意,您不能使用$(this)引用该字段
  6. 然后,您必须包括行return item;updater:选项中,所以输入字段实际上是使用item变量更新的。

我创建了一个包含该function的扩展。

https://github.com/tcrosen/twitter-bootstrap-typeahead

根据他们的文档 ,处理selected事件的正确方法是使用此事件处理程序:

 $('#selector').on('typeahead:select', function(evt, item) { console.log(evt) console.log(item) // Your Code Here }) 
 source: function (query, process) { return $.get( url, { query: query }, function (data) { limit: 10, data = $.parseJSON(data); return process(data); } ); }, afterSelect: function(item) { $("#divId").val(item.id); $("#divId").val(item.name); }