Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
26
rated 0 times [  31] [ 5]  / answers: 1 / hits: 73369  / 14 Years ago, thu, february 10, 2011, 12:00:00

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.


More From » jquery

 Answers
55

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);
}
}
}

[#93806] Tuesday, February 8, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
louiemarvinm

Total Points: 473
Total Questions: 103
Total Answers: 94

Location: Samoa
Member since Mon, Nov 8, 2021
3 Years ago
;