Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery UI AutoComplete: Only allow selected valued from suggested list

I am implementing jQuery UI Autocomplete and am wondering if there is any way to only allow a selection from the suggested results that are returned as opposed to allowing any value to be input into the text box.

I am using this for a tagging system much like the one used on this site, so I only want to allow users to select tags from a pre-populated list returned to the autocomplete plugin.

like image 306
stephen776 Avatar asked Feb 10 '11 00:02

stephen776


2 Answers

You could also use this:

change: function(event,ui){   $(this).val((ui.item ? ui.item.id : "")); } 

The only drawback I've seen to this is that even if the user enters the full value of an acceptable item, when they move focus from the textfield it will delete the value and they'll have to do it again. The only way they'd be able to enter a value is by selecting it from the list.

Don't know if that matters to you or not.

like image 196
Jason Gray Avatar answered Sep 24 '22 17:09

Jason Gray


I got the same problem with selected not being defined. Got a work-around for it and added the toLowerCase function, just to be safe.

$('#' + specificInput).autocomplete({    create: function () {     $(this).data('ui-autocomplete')._renderItem = function (ul, item) {       $(ul).addClass('for_' + specificInput); //usefull for multiple autocomplete fields       return $('<li data-id = "' + item.id + '">' + item.value + '</li>').appendTo(ul);      };   },    change:     function( event, ui ){       var selfInput = $(this); //stores the input field       if ( !ui.item ) {          var writtenItem = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val().toLowerCase()) + "$", "i"), valid = false;          $('ul.for_' + specificInput).children("li").each(function() {           if($(this).text().toLowerCase().match(writtenItem)) {             this.selected = valid = true;             selfInput.val($(this).text()); // shows the item's name from the autocomplete             selfInput.next('span').text('(Existing)');             selfInput.data('id', $(this).data('id'));             return false;           }         });          if (!valid) {            selfInput.next('span').text('(New)');           selfInput.data('id', -1);          }     } } 
like image 32
Victor Avatar answered Sep 21 '22 17:09

Victor