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 matching characters, the string is being escaped. So I see [strong]matching chars[/strong], instead of marked up text.
This is the javascript I’m currently using:
$("#autocompleteinputfield").autocomplete({
source: function (request, response) {
$.ajax({
url: "someservice",
type: "GET",
dataType: "json",
data: { filter: request.term, maxResults: 10 },
success: function (data) {
response($.map(data, function (item) {
// return { label: item.ID + ' - ' + item.Name, id: item.ID, value: item.Name }
var regex = new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + request.term.replace(/ ([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/ gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi");
return {
label: (item.ID + ' - ' + item.Name).replace(regex, "<strong>$1</strong>"),
id: item.ID,
value: item.Name
}
}))
}
});
},
select: function (event, ui) {
alert(ui.item ? ("You picked '" + ui.item.label + "' with an ID of " + ui.item.id)
: "Nothing selected, input was " + this.value);
}
});
Update :
“Input” is the text entered in a textbox (in this case : [input type="text" id="autocompleteinputfield" /]
Output looks like this:
[{"Description":"Nothing meaningful","ID":3,"Name":"Joe Public"}]
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:
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:
Update: With version >=1.10 of jQuery, there are some small modifications: