Is it possible to disable a list element in an autocomplete, so it is not chooseable (and greyed out)?
I have this code, taken from the jQuery UI example page:
HTML:
<input id="tags" />
jQuery:
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
As an example - is it possible to disable the last element if there are more than 3 items in the list?
In my real code, I have an AJAX request but I do not want to show more than 20 results in the autocomplete box, so if there are more than this, it should show something like "please narrow down your search" and disable the last element, so it is not chooseable (but only the last element should be disabled).
The above code is here with a Fiddle demo, http://jsfiddle.net/m6zvf/
Autocomplete attribute of HTML is use to fetch previous input values in input fields. Almost all browsers supports autocomplete attribute, by default this attribute is “on” in html. If you want to disable this attribute ,you can set autocomplete=”off” in html input tag.
Advertisements. Auto completion is a mechanism frequently used in modern websites to provide the user with a list of suggestions for the beginning of the word, which he/she has typed in a text box. The user can then select an item from the list, which will be displayed in the input field.
If I understand correctly you want to add a disabled option with the message saying to narrow down the search when the results are more than X, for that you'd need a custom response
and render methods:
Working fiddle
$(function () {
$("#tags").autocomplete({
source: availableTags,
response: function (event, ui) {
//Check if we have more than 3 results
if (ui.content.length > 3) {
//Remove all elements until there are only 3 remaining (the use of slice() was not supported)
while (ui.content.length > 3) {
ui.content.pop();
}
//Add message
ui.content.push({
'label': 'Please narrow down your search',
'value': ''
});
}
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
//Add the .ui-state-disabled class and don't wrap in <a> if value is empty
if(item.value ==''){
return $('<li class="ui-state-disabled">'+item.label+'</li>').appendTo(ul);
}else{
return $("<li>")
.append("<a>" + item.label + "</a>")
.appendTo(ul);
}
};
});
You can refer to the documentation for more info on the response method, the _renderItem
function is not documented but I found it in the source code of one of the examples
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