jQuery ui autocomplete when user does not select an option from the dropdown
Add a custom event of onchange
$('#Animal').change(function(){
var selectedValue = this.value;
// Do what you want here:
...
});
Or use the built-in change
event of the widget:
$('#Animal').autocomplete({
source: url,
minlength: 1,
select: function (event, ui) {
$("#Animal").val(ui.item.value);
changeUsersAnimal(ui.item.id);
}
change: function(event, ui) { // <=======
// ...
// ...
}
});
source
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.
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/