jQuery UI Autocomplete and Automatic Form Submit

Wednesday, April 4, 2012

It's a common to automatically submit a form after a user selects an item from an autocomplete list. The keyword here is "select" – it will lead you to handling the select event of the jQuery UI autocomplete widget.

someInput.autocomplete({
    source: data,
    select: function () {
        form.submit();
    }
});

This code will work as long as the user selects an item using the arrow keys and keyboard. The code doesn't work if the user selects an item using the mouse (the proper value doesn't appear in the input or the form submission).

The problem is the select event seems to be designed as more of a pre-processing event. You can implement your own custom selection logic and / or cancel the default logic by returning false from the method. You can also make sure the input is populated before submitting the form.

someInput.autocomplete({
    source: data,
    select: function (event, ui) {
        $(this).val(ui.item.value);
        form.submit();
    }
});

Comments
gravatar James Culbertson Thursday, April 5, 2012
Thanks for that Scott. I also ran into some related issues with the in its integration with ASP.Net MVC remote validation as it would only send the partial completion and had to further modify that function to suppress onkeyup and onfocusout events.

http://www.culbertsonexchange.com/wp/?p=190

gravatar PilotBob Friday, April 6, 2012
Wouldn't it be better to use the "change" event instead of the select event for this?
gravatar scott Friday, April 6, 2012
@PilotBob: That would work too, and with less work, but not until the input blurs (loses focus).
gravatar mohammad jafari Monday, May 28, 2012
tanks this is the best site
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!