How do I know if ENTER was used to select jQueryUI autocomplete clause or not?

Using jQuery 1.7.2 and jQueryUI 1.8.12, I am trying to implement an autocomplete field with the following behavior:

  • If an auto-complete suggestion is selected (using the mouse or keyboard), call function A
  • If there are no matches (therefore no suggestions were suggested) and ENTER is pressed, call function B

The problem I am facing is that when I select a sentence using the keyboard, my check for ENTER also starts, and this forces me to call function B when I do not. Here is a simple example (also on jsfiddle ):

$('input').autocomplete({ source: ['foo', 'bar', 'baz' ], select: function(event, ui) { console.log('suggestion selected'); } }).keydown(function(e) { if(e.keyCode == 13) console.log('ENTER (keydown)'); }).keyup(function(e) { if(e.keyCode == 13) console.log('ENTER (keyup)'); }); 

According to the console, keyup / keydown handlers are fired after an autocomplete selection event (which is strange), so I tried to prevent it (by trying top spoofing, default prevention, or both). I also traversed the properties of the originalEvent event object to the highest parent (original KeyboardEvent), but this too cannot be stopped.

Does anyone know a simple solution to what I'm trying to execute, preferably avoiding flags to indicate that the select event was fired? I would like to avoid this, since such a flag should be cleared elsewhere, which seems unacceptable.

+4
source share
3 answers

How about this one. Before logging keydown events, simply bind the autocomplete.keydown event. This is guaranteed to be done before your close. Please note that the order in which events are recorded also matters.

http://jsfiddle.net/zFPZH/

 $('input') .autocomplete({ source: ['foo', 'bar', 'baz' ], select: function(event, ui) { console.log('suggestion selected'); } }).bind("keydown.autocomplete", function() { if(event.keyCode == 13){ console.log('keydown.autocomplete (keyup)'); }; }).keydown(function(e) { if(e.keyCode == 13){ console.log('ENTER (keydown)'); }; }).keyup(function(e) { if(e.keyCode == 13){ console.log('ENTER (keyup)'); }; }); 
+3
source

It seems that when the list of offers appears and the offer is highlighted, it has a ui-state-hover class. When checking the key code in your keydown event keydown you can also check for the presence of an element with this class in the offers menu to see if this input will confirm this offer.

+1
source

This is an old question, but none of these answers worked for me.

I ended up with this workaround:

 $('input') .autocomplete({ source: ['foo', 'bar', 'baz' ], select: function(event, ui) { $(this).data("stopPropagation", true); // <----- turn off console.log('suggestion selected'); } }).keydown(function(e) { if ($(this).data("stopPropagation")) { $(this).data("stopPropagation", false); // <----- turn on return; } if (e.keyCode == 13){ console.log('ENTER (keyup)'); }; }); 
0
source

All Articles