I\'m using the autocomplete function in jQuery UI 1.8.6. And I want to highlight matching results. But for some reason when I use a regex to add \"strong\" tags around the m
The jQuery autocomplete source code is the culprit. If you look in the actual javascript files, you'll find this definition for displaying items in the autocomplete list:
_renderItem: function( ul, item) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( $( "<a></a>" ).text( item.label ) )
.appendTo( ul );
}
You'll see it's appending ".text(item.label)" which causes the html to be escaped. To solve this, you kind of have to put in a hack to override this "_renderItem" method, replacing the line that appends the label as plain text with a line that appends the label as html. So update your code like this:
$(function () {
$("#autocompleteinputfield").autocomplete({
// leave your code inside here exactly like it was
})
.data('autocomplete')._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( '<a>' + item.label + '</a>' )
.appendTo( ul );
};
});
Update: With version >=1.10 of jQuery, there are some small modifications:
$(function () {
$("#autocompleteinputfield").autocomplete({
// leave your code inside here exactly like it was
})
.data('ui-autocomplete')._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "ui-autocomplete-item", item )
.append( '<a>' + item.label + '</a>' )
.appendTo( ul );
};
});
$.extend($.ui.autocomplete.prototype, {
_renderItem: function (ul, item) {
var searchMask = this.element.val();
var regEx = new RegExp(searchMask, "ig");
var replaceMask = "<b style=\"color:green;\">$&</b>";
var html = item.label.replace(regEx, replaceMask);
return $("<li></li>")
.data("item.autocomplete", item)
.append($("<a></a>").html(html))
.appendTo(ul);
}
});
Plain javascript alert() does not display html. Look into using a modal or something else. Or like the others said, post some specific input/output.