Reputation: 1441
I have a text input element that uses jQuery UI Autocomplete. The input has an onchange
event bound to it to change some other form values based on the user's selection. I also want to change those other form values when the user selects an option from the autocomplete.
The problem is that if a user is looking up "beer", but only types "bee" and then clicks on the beer option in the autocomplete, the input's onchange
fires with a value of "bee", and then the autocomplete's select function fires (with the correct value of "beer"). Since both of these handlers utilize an ajax call to lookup some stuff, I get into a race condition.
My question is: Is there some way that I can have the onchange
either not fire, or abort, in the case where a user clicked on an autocomplete option. Note: this only happens when clicking, selecting an option using only the keyboard does not fire the input's onchange
.
It's not an option for me to just disable the onchange
entirely when the autocomplete is active, since it's believable that the user will just keep typing, and exit out of the input without selecting anything from the autocomplete.
I've done a fair bit of console.log()
'ing, and the onchange
event fires before all other events I can think of, including the input's focusout
, the autocomplete's item's focus, etc.
Upvotes: 4
Views: 4131
Reputation: 126042
This problem is precisely the reason for autocomplete's change
event. It sounds like you should be able to leverage this event to perform logic based on whether or not the user selected an item (thereby removing your onchange
and autocompleteselect
event handlers). For example:
$("#auto").autocomplete({
source: ['hi', 'bye', 'foo', 'bar'],
change: function (event, ui) {
if (ui.item) {
/* user selected an item */
} else {
/* user entered a new item */
}
}
});
Example: http://jsfiddle.net/bdDs7/
Upvotes: 4