Using jQuery 1.7.2 and jQueryUI 1.8.12, I'm trying to implement an autocomplete field with the following behavior:
- If an autocomplete suggestion is selected (with the mouse or keyboard), call function A
- If there are no matches (hence no suggestion was selected) and ENTER was pressed, call function B
The problem I'm having is, when I select a suggestion with the keyboard, my check for ENTER is also fired, and that would make me call function B when I shouldn't. 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, the keyup/keydown handlers are firing after the autocomplete select event (which is weird), so I tried to prevent it (by either trying to top bubbling, preventing the default, or both). I also traversed the event object's originalEvent
properties up to the topmost parent (the original KeyboardEvent), but that seems unstoppable either.
Does anyone know a simple solution to what I'm trying to accomplish, preferably avoiding flags to indicate that the select event was fired? I'd like to avoid that, as such a flag would have to be cleared somewhere else, which seems error-prone.