ENHANCED Highlighting Autocomplete Text
Visually highlighting matched text in jQuery UI autocomplete menu items.
HTML
<div class="ui-widget">
<input placeholder="ui-state-highlight" />
</div>
<div class="ui-widget">
<input placeholder="bold-text" />
</div>
CSS
body {
font-size: 0.8em;
}
.bold-text {
font-weight: bold;
color: red;
}
JavaScript
(function( $ ) {
// Custom autocomplete instance.
$.widget( "app.autocomplete", $.ui.autocomplete, {
// Which class get's applied to matched text in the menu items.
options: {
highlightClass: "ui-state-highlight"
},
_renderItem: function( ul, item ) {
// Replace the matched text with a custom span. This span uses the class found in the "highlightClass" option.
var re = new RegExp( "(" + this.term + ")", "gi" ),
cls = this.options.highlightClass,
template = "<span class='" + cls + "'>$1</span>",
label = item.label.replace( re, template );
return $( "<li>" )
.attr('id', item.id)
.attr( "data-value", item.value )
.append( $( "<a>" ).html( label ) )
.appendTo( ul );
}
});
// Demo data for autocomplete source.
var tags = [
{id : 0, label:"ActionScript"},
{id : 1, label:"AppleScript"},
{id : 2, label:"Asp"},
{id : 3, label:"BASIC"},
{id : 4, label:"C"},
{id : 5, label:"C++"},
{id : 6, label:"Clojure"},
{id : 7, label:"COBOL"},
{id : 8, label:"ColdFusion"},
{id : 9, label:"Erlang"},
{id : 10, label: "Fortran"},
{id : 11, label: "Groovy"},
{id : 12, label: "Haskell"},
{id : 13, label: "Java"},
{id : 14, label: "JavaScript"},
{id : 15, label: "Lisp"},
{id : 16, label: "Perl"},
{id : 17, label: "PHP"},
{id : 18, label: "Python"},
{id : 19, label: "Ruby"},
{id : 20, label: "Scala"},
{id : 21, label: "Scheme"}
];
// Create autocomplete instances.
$(function() {
var autocompleteSelect = function( event, ui ) {
var item = ui.item;
console.log(item.id, item.label,...