How do I add a custom class to the ui-autocomplete div? I have multiple autocomplete widgets loading on my page and some of their drop downs need to be styled differently so I can't just edit the ui-autocomplete class. I am working with the jQuery UI combobox code (http://jqueryui.com/autocomplete/#combobox) and, by altering that code, I would like to add a class to the created ui-autocomplete div.
5 Answers
$("#auto").autocomplete({
source: ...
}).autocomplete( "widget" ).addClass( "your_custom_class" );
3 Comments
user1032531
Adds a class to the input, but not the associated autocomplete list.
karmasponge
The question refers to the 'drop downs' requiring styling and this only modifies the input.
be3
Uncaught Error: cannot call methods on autocomplete prior to initialization; attempted to call method 'widget'
Simply use the classes argument:
$("#auto").autocomplete({
classes: {
"ui-autocomplete": "your-custom-class",
},
...
});
This means that wherever jQuery UI applies the ui-autocomplete class it should also apply your-custom-class.
This is relevant to any jQuery UI widget, not just Autocomplete. See the documentation.
2 Comments
ron
This is the definitive answer according to the documentation. But it's very important to note that it requires version 1.21.1. It doesn't seem to work on autocomplete in earlier versions.
Philip Stratford
I think @ron means that version 1.12.1 is required, since that's the latest version. Just to save everyone else a visit to the docs.
Sorry for delay). Have a look at code below.
$(function () {
$("#auto").autocomplete({
source: ['aa', 'bb', 'cc', 'dd']
}).data("ui-autocomplete")._renderItem = function (ul, item) {
ul.addClass('customClass'); //Ul custom class here
return $("<li></li>")
.addClass(item.customClass) //item based custom class to li here
.append("<a href='#'>" + item.label + "</a>")
.data("ui-autocomplete-item", item)
.appendTo(ul);
};
});
Comments
Use this method to add custom classes to drop down box
_renderMenu: function( ul, items ) {
var that = this;
$.each( items, function( index, item ) {
that._renderItemData( ul, item );
});
$( ul ).find( "li:odd" ).addClass( "odd" );
}
1 Comment
Colin
I added that exact snippet to my code and nothing happened. When does that method supposedly run? I added immediately after the _create: method
I managed to get it working by following the documentation and by updating my jquery version to v1.12.4 at least (required by jquery classes options) and then updating also the jquery-ui version accordingly (v1.12.1)