autocomplete ._renderItem and adding a Class to wrapper
Asked Answered
D

3

8

Going off the example here http://jqueryui.com/demos/autocomplete/#custom-data I'm wondering how to add a style to the ul wrapper when using _renderItem():

    .data( "autocomplete" )._renderItem = function( ul, item ) {
        return $( "<li></li>" )
            .data( "item.autocomplete", item )
            .append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
            .appendTo( ul );
    };
Dejection answered 18/2, 2012 at 1:46 Comment(0)
G
26

Here would be one simple way to do it, tapping into the open event:

$("#auto").autocomplete({
    source: /* ... */,
    open: function () {
        $(this).data("autocomplete").menu.element.addClass("my_class");
    }
});

jQueryUI >= 1.9

$("#auto").autocomplete({
    source: /* ... */,
    open: function () {
        $(this).data("uiAutocomplete").menu.element.addClass("my_class");
    }
});

menu is an internal widget that autocomplete uses.

Example: http://jsfiddle.net/bx8Ye/

Grasping answered 18/2, 2012 at 2:58 Comment(1)
Just use $(this).data('uiAutocomplete') instead of 'autocomplete' for these versions.Rye
G
3

If you want to add a style to the ul wrapper then you need to overload _renderMenu() and not _renderItem().

Here is an example that sets the width of the UL and adds a footer as the last li in the ul

.data( "autocomplete" )._renderMenu = function( ul, data ) {

    var self = this;
    $(ul).css('width', settings.dropDownWidth);

    $.each( data, function( index, item ) {
        self._renderItem( ul, item );
    });

    $(ul).append("<div class='myFooter'>some footer text</div>");
}; 
Grandaunt answered 18/2, 2012 at 1:57 Comment(6)
ERROR: self._renderItem( ul, item ); is not a functionDejection
ERROR: self = this.css("width", "900px"); this.css is not a functionDejection
Sorry about that, it was meant as an example not something you can cut and paste and just use.Grandaunt
here is a link to someone who answered the question better than I did... #2436464Grandaunt
edited the answer to correct the bugs you pointed out. Let me know if that doesn't work for you.Grandaunt
@Grandaunt ul is already a jQuery object, no need to $(ul)Habitual
E
1

When using jQuery UI 1.10, I used Andrew Whitaker's answer, but I had to change

$(this).data("autocomplete").menu.element.addClass("my_class");

to

$(this).data("uiAutocomplete").menu.element.addClass("my_class");
Epitome answered 15/5, 2013 at 13:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.