jQuery - Preventing autocomplete select triggering blur()

m0dE picture m0dE · Apr 19, 2011 · Viewed 18.7k times · Source

I'm trying to prevent blur to happen when select: in autocomplete is called. (select: is called when the item is clicked on suggestion box of autocomplete) However, unintentionally, blur is called when I select an item from a suggestion box. How would I fix this problem?

Here's how my code is basically lined up.

$("#input_field").autocomplete({
    source: "source.php",
    select: function( event, ui ) { alert("Item selected! Let's not trigger blur!"); }
}).blur(function(event) {
    alert("Alert if the user clicked outside the input, pressed enter, or tab button.");
    alert("But not from the item selection! :S");
});

Thank you!

Edit: Here's a brief context. I am trying to allow users to search/select an item or create a new item if the user blurs the input.

Answer

Jon Snyder picture Jon Snyder · Dec 14, 2011

The autocomplete jquery UI widget comes with a "change" event which I think does what you want. It is called just like a blur, except it isn't called when an item is selected with the mouse.

$("#input_field").autocomplete({
    source: "source.php",
    select: function( event, ui ) { alert("Item selected! Let's not trigger blur!"); }
});
$("#input_field").bind('autocompletechange', function(event, ui) {
    alert("Alert if the user clicked outside the input, pressed enter, or tab button.");
    alert("But not from the item selection! :S");
});