8

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

curiousdork
  • 1,034
  • 2
  • 12
  • 13

2 Answers2

9

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");
        }
    });
cdeszaq
  • 30,869
  • 25
  • 117
  • 173
  • 1
    Thanks mucho! I'll play around with it. So far, I did the following: `open: function (event, ui) { //$("ul.ui-autocomplete.ui-menu .ui-menu-item:odd").css("background-color", "#dedede"); var url = "Can't find the item? Request to add a new item!"; $("ul.ui-autocomplete.ui-menu").append(url); }` It looks like I can append an item to the end of the list, now gotta make sure it's a clickable URL. – curiousdork Apr 19 '11 at 15:16
1

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.

Cheeso
  • 189,189
  • 101
  • 473
  • 713
  • This seems pretty brittle. If the UI team decided to update how the `_renderMenu` function worked, you would need to update your own code, since `_renderMenu` isn't part of the public API. – cdeszaq Apr 18 '11 at 16:41
  • Yes, exactly, that's why it's called *monkeypatching*. See http://stackoverflow.com/questions/2435964/jqueryui-how-can-i-custom-format-the-autocomplete-plug-in-results/2436493#2436493 for more details on the technique. – Cheeso Apr 25 '11 at 10:35