Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 893
JK. Avatar asked May 01 '12 23:05

JK.


2 Answers

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/

like image 71
Andrew Whitaker Avatar answered Sep 23 '22 00:09

Andrew Whitaker


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.

like image 38
Marques Avatar answered Sep 23 '22 00:09

Marques