jQuery ui autocomplete when user does not select an option from the dropdown

jquery, jquery-ui, jquery-ui-autocomplete

Solution

You're probably looking for Scott González' `autoSelect` extension. Just including this extension on the page will allow the `select` event to fire if the user enters a valid value and should require no changes on your end:

/*
 * jQuery UI Autocomplete Auto Select Extension
 *
 * Copyright 2010, Scott González (http://scottgonzalez.com)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * http://github.com/scottgonzalez/jquery-ui-extensions
 */
(function( $ ) {

$.ui.autocomplete.prototype.options.autoSelect = true;
$( ".ui-autocomplete-input" ).live( "blur", function( event ) {
    var autocomplete = $( this ).data( "autocomplete" );
    if ( !autocomplete.options.autoSelect || autocomplete.selectedItem ) { return; }

    var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" );
    autocomplete.widget().children( ".ui-menu-item" ).each(function() {
        var item = $( this ).data( "item.autocomplete" );
        if ( matcher.test( item.label || item.value || item ) ) {
            autocomplete.selectedItem = item;
            return false;
        }
    });
    if ( autocomplete.selectedItem ) {
        autocomplete._trigger( "select", event, { item: autocomplete.selectedItem } );
    }
});

}( jQuery ));

Here's an example using the extension: http://jsfiddle.net/vFWUt/226/

Problem

When using the jquery autocomplete plugin, what do you do when the user does not select an item in the list, but instead types a valid value and tabs away? eg when the auto complete list contains: ``` Cat Dog Fish ``` And the user types `cat`, but does not select `Cat` from the autocomplete's dropdown list and instead tabs away. Because they did not select any item from the list, the autocomplete select event does not fire, and we lose the chance to respond to it: ``` $('#Animal').autocomplete({ source: url, minlength: 1, select: function (event, ui) { $("#Animal").val(ui.item.value); changeUsersAnimal(ui.item.id); } }); ``` How do I handle this case?

Original source

Related problems