How to bind a keystroke event in jquery autocomplete?

As you can see at http://jsfiddle.net/hn838/4/ 'click' works fine for autocomplete, but I want to run the same code when entering the keypress key as well, but it does not work for me. My code is here for both. Click:

$('.ui-autocomplete').on('click', '.ui-menu-item', function(){ $('.college').trigger('click'); }); 

Keyprss:

  $('.ui-autocomplete').on('keypress', '.ui-menu-item', function(e){ if (e.which == 13) { e.preventDefault(); $('.college').trigger('click'); } }); 

I want to execute $('.college').trigger('click'); on click and enter keypress . click works fine but clicks not working.any button?

+4
source share
2 answers

Instead of binding to key events, you can add a function to the select event:

 select: function(){ $('.college').trigger('click'); } 

Thus, it only works when the user actually selects an autocomplete value.

http://jsfiddle.net/louisbros/hn838/10/

+6
source

There is no ui-autocomplete class in your fiddle. Therefore, I assume that it looks like this:

 <input type = 'text' class = 'search ui-autocomplete' /> 

and also there is no ui-menu-item class in your fiddle, so you should do like this:

 $('.ui-autocomplete').on('keypress', function(e){ if (e.which == 13) { e.preventDefault(); $('.college').trigger('click'); } }); 

Updated Fiddle


If you want to use a class that is automatically created from the jQuery user interface, you can do:

 $('.ui-autocomplete-input').on('keypress', function(e){ if (e.which == 13) { e.preventDefault(); $('.college').trigger('click'); } }); 

Fiddle

+2
source

All Articles