user67867
user67867

Reputation: 421

Make matched letters highlighted in autocomplete in javascript/jquery

I have a set of airport names along with their codes to be displayed in autocomplete.

E.g. Amsterdem (AMS)

I want to match the value entered in the search box,I want to display the matched airport name as well as airportcode bold as follows.

if I enter ams in search box,i want to highlight 'Ams'terdem ('AMS') in my autocomplete.

I have written a code as below:

function () {
    var oldFn = $.ui.autocomplete.prototype._renderItem;
    $.ui.autocomplete.prototype._renderItem = function( ul, item) {
        var re = new RegExp("^" + this.term, "i") ;
        var t = item.label.replace(re,"<span style='font-weight:bold;'>" + this.term + "</span>");
        return $( "<li></li>" )
            .data( "item.autocomplete", item )
            .append( "<a>" + t + "</a>" )
            .appendTo( ul );
    };
};

it results as 'Ams'terdem (AMS) instead of 'Ams'terdem (AMS).

Note:Amsterdem (AMS) is a single term

Please advice.

Upvotes: 0

Views: 1684

Answers (1)

Jeetendra Chauhan
Jeetendra Chauhan

Reputation: 1977

you have to change

var re = new RegExp("^" + this.term, "i") ;

with this code

var re = new RegExp(this.term, "ig") ;

this will replace all instance in your string

"^" denotes start of string, and "g" in regular expression works on all instance

here is working example

replace your code with this one

function () {
var oldFn = $.ui.autocomplete.prototype._renderItem;
$.ui.autocomplete.prototype._renderItem = function( ul, item) {
    var re = new RegExp(this.term, "ig") ;
    var t = item.label.replace(re,"<span style='font-weight:bold;'>" + this.term + "</span>");
    return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( "<a>" + t + "</a>" )
        .appendTo( ul );
};
};

Upvotes: 1

Related Questions