Select the first sentence from Typeahead.js when pressing Enter key in the field

I want to select the first available sentence from the Typeahead.js sentence elements when I press the Enter key while I focus on that field.

I got this code:

$('#cities-prefetch .typeahead').on('keyup', function(e) {
    if(e.which == 13) {
        var value = $('input:text#city').typeahead('val');
    }
});

      

But this only selects the currently selected value from s in the field itself.

Please, help!

+3


source to share


5 answers


You can call click

on the first sentence 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 Demo

+11


source


You can use autoselect

- If true

, typeahead will automatically select the first sentence when the Enter key is pressed. By default false

. refrence



+2


source


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();
    }
});

      

+2


source


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');    
        } 
    }
});

      

0


source


$(element).on('keyup', function(e) {
  if(e.which == 13) {
    e.preventDefault();
    var selectables = $(element).siblings(".tt-dropdown-menu").find(".tt-suggestion");
    if (selectables.length > 0) {
      $(selectables[0]).trigger('click');
    } else {
        $(butto_element).trigger('click');
    }
  }
});

      

0


source







All Articles