I want to select first available suggestion from Typeahead.js suggestion items, when I hit Enter key while I'm focused on that field.
I got this code by now:
$('#cities-prefetch .typeahead').on('keyup', function(e) {
if(e.which == 13) {
var value = $('input:text#city').typeahead('val');
}
});
But that only fetches the current selected value from with in the field itself.
Please help!
You could trigger a click
on the first suggestion if the Enter key is pressed
$('#cities-prefetch .typeahead').on('keyup', function(e) {
if(e.which == 13) {
$(".tt-suggestion:first-child", this).trigger('click');
}
});
See this Demo
this worked in my case.
$('[id$=_form]').on('keydown', '.twitter-typeahead #input_id', function(e) {
if(e.which == 13) {
e.preventDefault();
$('.tt-selectable').first().click();
}
});
In typeahead.js 0.11.1 this seems to do the trick for me.
$(element).on('keyup', function(e) {
if(e.which == 13) {
e.preventDefault();
//find the selectable item under the input, if any:
var selectables = $(element).siblings(".tt-menu").find(".tt-selectable");
if (selectables.length > 0){
$(selectables[0]).trigger('click');
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With