回答

27
$('.typeahead').on('typeahead:selected', function(evt, item) { 
    // do what you want with the item here 
}) 
+2

https://github.com/twitter/typeahead.js是不同於Bootstrap typeahead – Utopik 2013-06-10 14:08:44

+0

這種方法適用於https://twitter.github.io/typeahead.js/而不是Twitter的引導。 (typeahead現在從twitter引導分開) – 2015-06-24 16:13:32

+0

有沒有什麼辦法可以讓這個處理程序按下鍵? evt var似乎沒有一個'which'propery – HussienK 2016-06-09 20:55:02

5

我第一次公佈的答案就在這裏(大量運行JavaScript函數剛過用戶選擇一個值但我在這裏找到了答案),所以這裏是我的貢獻,希望它有幫助。你應該能夠檢測到一個變化 - 試試這個:

function bob(result) { 
    alert('hi bob, you typed: '+ result); 
} 

$('#myTypeAhead').change(function(){ 
    var result = $(this).val() 
    //call your function here 
    bob(result); 
}); 
+1

已經下降,因爲這不是支持,也不是推薦的方式來處理typeahead上的選定元素,請看這裏:https://github.com/twitter/typeahead.js在:typahead:已選擇 – Oddman 2013-10-22 05:50:09

2

我創建了一個包含該功能的擴展。

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

+1

鏈接現在被破壞。是這樣的存儲庫?https://github.com/tcrosen/twitter-bootstrap-typeahead – tsellon 2012-04-27 21:50:21

+0

對不起,我更新了鏈接前一段時間,截至4月29日它的工作原理。 – Terry 2012-07-19 13:43:36

12
$('.typeahead').typeahead({ 
    updater: function(item) { 
     // do what you want with the item here 
     return item; 
    } 
}) 
+0

官方的方式來做什麼要求和工作:) – PierrickM 2013-05-28 15:54:30

5

要獲取預輸入工作方式的解釋,你想在這裏做,採取下面的代碼示例什麼:

HTML輸入字段:

<input type="text" id="my-input-field" value="" /> 

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. 必須然後在updater:選項內包含行return item;,所以輸入字段實際上更新與item變量。
1

根據他們documentation,處理selected事件的正確方式是使用此事件處理程序:

$('#selector').on('typeahead:select', function(evt, item) { 
    console.log(evt) 
    console.log(item) 
    // Your Code Here 
}) 
0
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); 

} 
相關問題