Autocomplete and bold highlight
I've gone from the Jorn autocomplete plugin to the jQuery UI autocomplete plugin. Not sure why, because I liked Jorn's plugin but it feels better to use jQuery UI. Here's my hack to make the searched for work highlit.
- $('#id_q').autocomplete({
source: function(request, response) {
$.ajax({
url: AUTOCOMPLETE_URL,
dataType: 'json',
data: { q: request.term },
success: function(data) {
response($.map(data, function(item) {
return {label: __highlight(item.title, request.term) + " (" + item.type + ")",
value: item.title};
}));
}
});
},
minLength: 2)
.data( "autocomplete" )._renderItem = function( ul, item ) {
// only change here was to replace .text() with .html()
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( $( "<a></a>" ).html(item.label) )
.appendTo( ul );
};
The highlight function might need some work but it works.
- function __highlight(s, t) {
var matcher = new RegExp("("+$.ui.autocomplete.escapeRegex(t)+")", "ig" );
return s.replace(matcher, "<strong>$1</strong>");
}