jQuery UI Autocomplete Formatting for Multiple Elements
I have the jQuery UI Autocomplete setup to my liking and working perfectly, but there is one fatal flaw. In my autocomplete I use a custom display like this example. I have something very similar built but with on exception...
The only difference is that I have multiple autocomplete elements of the same class on that one page. Only the first element shows the extra data line, the rest only show the basic autocomplete.
I can get the desired result by just iterating all of thos开发者_开发问答e class elements and calling the autocomplete on them, but I was hoping there was a better way of calling it once and having it "just work".
Here's how I'm adding the extra line:
.data( 'autocomplete' )._renderItem = function( ul, item ) {
return $( '<li></li>' )
.data( 'item.autocomplete', item )
.append( '<a>' + item.label + '<br/><small>' + item.desc + '<small></a>' )
.appendTo( ul );
};
I should note that I'm not getting any console exceptions at all.
The only way I can make this work is by changing my code from:
addautocomplete($('.tagEntry'));
To:
$('.tagEntry').each(function() {
addautocomplete(this);
});
You simply need to override the function via the object prototype, instead of on a single instance.
$.ui.autocomplete.prototype._renderItem = function( ul, item ) {
return $( '<li></li>' )
.data( 'item.autocomplete', item )
.append( '<a>' + item.label + '<br/><small>' + item.desc + '<small></a>' )
.appendTo( ul );
};
Overwrite the function before activating any autocompletes, but after the script has loaded.
Alternatively:
$(..).autocomplete(..).each(function () {
$.data(this, "autocomplete")._renderItem = function (ul, item) { ... } })
I had the same issue as sshefer and I got the best solution for it:
Change the
.autocomplete( "instance" )._renderItem = function( ul, item )by
$( ".input_class" ).each(function(){
$( this ).autocomplete( "instance" )._renderItem = function( ul, item )...
});
精彩评论