Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select first suggestion from Typeahead.js when hit Enter key in the field

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!

like image 529
Duvdevan Avatar asked Nov 06 '14 16:11

Duvdevan


3 Answers

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

like image 53
Sam Battat Avatar answered Nov 10 '22 18:11

Sam Battat


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();
    }
});
like image 23
DrLulz Avatar answered Nov 10 '22 18:11

DrLulz


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');    
        } 
    }
});
like image 1
Johnny O Avatar answered Nov 10 '22 18:11

Johnny O