Handle selected event in twitter bootstrap Typeahead?
$('.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;
}
})
For an explanation of the way typeahead works for what you want to do here, taking the following code example:
HTML input field:
<input type="text" id="my-input-field" value="" />
JavaScript code block:
$('#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;
}
})
Explanation:
- Your input field is set as a typeahead field with the first line:
$('#my-input-field').typeahead(
- When text is entered, it fires the
source:
option to fetch the JSON list and display it to the user. - If a user clicks an item (or selects it with the cursor keys and enter), it then runs the
updater:
option. Note that it hasn't yet updated the text field with the selected value. - You can grab the selected item using the
item
variable and do what you want with it, e.g.myOwnFunction(item)
. - I've included an example of creating a reference to the input field itself
$fld
, in case you want to do something with it. Note that you can't reference the field using $(this). - You must then include the line
return item;
within theupdater:
option so the input field is actually updated with theitem
variable.