Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending an item to a jQuery UI autocomplete

Currently, I'm using jQuery UI autocomplete on a textbox that references an ASHX file.

Everything is working propertly, except I want to append an item at the end of the list that reads: "Item not found? Click here to request to add a new item."

I tried the following the lines of code, but all it did was format the item's, I was unable to append.

data( "catcomplete" )._renderItem = function( ul, item ) {
        return $( "<li></li>" )
            .data( "item.catcomplete", item )
            .append( $( "<a class='ui-menu-item'></a>" ).text( item.label ) )
            .appendTo( $('ul').last('.autocomplete-category'));
    };

Hints? Tips? Mucho gracias! :D

like image 424
curiousdork Avatar asked Apr 18 '11 16:04

curiousdork


2 Answers

You should add your extra entry after the Open event fires. That will give you access to the list, which is what you are after, rather than to each element, which is what the _renderItem is giving you access to.

Here's an example styling the entries that have been populated into the list:

$("#myBox").autocomplete({
        source: "[URL]",
        minLength: 2,
        open: function(event, ui) {
            $("ul.ui-autocomplete.ui-menu .ui-menu-item:odd").css("background-color","#dedede");
        }
    });
like image 198
cdeszaq Avatar answered Sep 20 '22 20:09

cdeszaq


You don't want to fiddle with _renderItem. That is the fn that renders one item; it is called once for each item in the list of suggestions.

What you want to do is monkeypatch the _renderMenu function. The original definition in jQuery UI 1.8.6 is like this:

_renderMenu: function( ul, items ) {
    var self = this;
    $.each( items, function( index, item ) {
        self._renderItem( ul, item );
    });
},

It's probably basically the same for other versions of jQuery UI.

Patch this to add your extra item, after doing the $.each.

like image 36
Cheeso Avatar answered Sep 20 '22 20:09

Cheeso