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