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?
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/
With jQuery version >= 1.8.11 use the autoFocus option set to true
$( ".selector" ).autocomplete({ autoFocus: true });
That has the additional advantage of automatically selecting the first item in the list so the user can just press Enter or Tab to select it without having to type all the name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With