开发者

How to patch *just one* instance of Autocomplete on a page?

开发者 https://www.devze.com 2023-03-09 03:58 出处:网络
This answer --jQueryUI: how can I custom-format the Autocomplete plug-in results?-- describes how to monkeypatch the jqueryUI autocomplete widget, so that it displays things in a particular way. The a

This answer -- jQueryUI: how can I custom-format the Autocomplete plug-in results? -- describes how to monkeypatch the jqueryUI autocomplete widget, so that it displays things in a particular way. The approach it uses is to replace a function on the $.ui.autocomplete.prototype.

This means that all autocomplete widgets will get this patch.

Is there a way to patch the autocomplete widget for just one input element? What is it?

When I examine $('$input')开发者_开发知识库.autocomplete , I don't see any of the autocomplete fns there (_renderItem, _renderMenu, _search, etc).


Check out the custom data and display demo. This demo is not modifying the prototype object of the autocomplete widget, meaning that only that instance of the widget is effected:

$("selector").autocomplete({ ... }).data( "autocomplete" )._renderItem = function( ul, item ) {
    return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
        .appendTo( ul );
};

Here's a working demo: http://jsfiddle.net/vJSwq/


The code from Andrew Whitaker just work for one autocomplete input. If you select more than one input-element, the second autocomplete widget dosn't show any entrys. You have to add a foreach to handel all selected input elements like mentioned here

$("selector")
.autocomplete({ ... })
.each(function () {
    $(this).data("autocomplete")._renderItem = function( ul, item ) {
        return $("<li></li>")
            .data("item.autocomplete", item)
            .append("<a>" + item.label + "<br>" + item.desc + "</a>")
            .appendTo(ul);
    };
);


For recent versions of jQuery(1.8+) / jQuery UI (1.10+), you should use:

$("selector").autocomplete({ ... }).data('uiAutocomplete')._renderItem = function( ul, item ) {
    return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
    .appendTo( ul );
};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号