I am wondering how to make the matched part of the autocomplete suggestions bold when using jquery ui autocomplete?
So for example if you type in \"ja\" and the sugg
I'm not sure why the autocomplete is so bare-bone compared to the other functionalities it contains (e.g. droppable, sortable, draggable etc.).
It should really offer you with a stylable option, e.g. wrapping it with <span class="ui-autocomplete-term">term</span>
or something similar.
You could do it like this
It should be pretty self-explanatory; if not, gimme a shout.
In jQuery UI 1.11.1, here is the code I used to make it work (case insensitive):
open: function (e, ui) {
var acData = $(this).data('ui-autocomplete');
acData
.menu
.element
.find('li')
.each(function () {
var me = $(this);
var keywords = acData.term.split(' ').join('|');
me.text(me.text().replace(new RegExp("(" + keywords + ")", "gi"), '<b>$1</b>'));
});
}
If you are using jquery-ui.js:
acData = $(this).data('autocomplete');// will not work
//instead use
acData = $(this).data('uiAutocomplete');
Here's a solution for those who want to search case insensitive (only the open function is diffirent):
open: function(e,ui) {
var
acData = $(this).data('autocomplete');
acData
.menu
.element
.find('a')
.each(function() {
var me = $(this);
var regex = new RegExp(acData.term, "gi");
me.html( me.text().replace(regex, function (matched) {
return termTemplate.replace('%s', matched);
}) );
});
}
In jQuery UI 1.9.x this solution did not work for me because acData was undefined - the data reference timing was wrong because I init my PluginHelper before the document ready.
I came up to mod the _renderItem using jQuery UIs widget factory:
$.widget("custom.autocompleteHighlight", $.ui.autocomplete, {
_renderItem: function (ul, item) {
var regexp = new RegExp('(' + this.term + ')', 'gi'),
classString = this.options.HighlightClass ? ' class="' + this.options.highlightClass + '"' : '',
label = item.label.replace(regexp, '<span' + classString + '>$1</span>');
return $('<li><a href="#">' + label + '</a></li>').appendTo(ul);
}
});
You now can use it with:
$('input.jsAutocompleteHighlight').autocompleteHighlight({
highlightClass: 'ui-autocomplete-highlight'
});
CSS styling:
.ui-autocomplete-highlight {
font-weight: bold;
}