palash gandhi
palash gandhi

Reputation: 87

jQuery UI autocomplete highlight full word instead of matched substring

I am creating an autocomplete feature. It all works fine. But I need to highlight the entire word that contains the matched text. For example:

src = ['Apple', 'America', 'Apes', 'Battle of the Apes']

If a user types "Ap" I get

Apple
Apes
Battle of the Apes

What I want:

Apple
Apes
Battle of the Apes

$(document).ready(function(){
    $("#searchresult").autocomplete({
        source       :'autocomplete.php',
        minLength    : 1,
        selectFirst  : true,
        matchContains: true,
        scroll       : false,
        appendTo     : '#menucontainer',
        autoFocus    : true,
        select       : function( event, ui ) { 
            window.location.href = ui.item.value;
            ui.item.value=ui.item.label;
        }
    })
    .data( "autocomplete" )._renderItem = function( ul, item ) {
        var term = this.element.val(),
            regex = new RegExp( '(' + term + ')', 'gi' );
        t = item.label.replace( regex , "<b>$&</b>" );
        return $( "<li></li>" ).data("item.autocomplete", item)
            .append( "<a style='height:30px;'><div style='width: 100%; float: left;overflow: hidden; white-space:nowrap; text-overflow: ellipsis; text-align: left;'>" + t + "</div><div style='right: 0; position: relative; float:right; font-size: 11px;margin-top:-15px; color: #b3b3b3;'>" + item.cate + "</div></a>")
            .appendTo( ul );
    }
});

Upvotes: 3

Views: 2365

Answers (1)

M&#225;rio Areias
M&#225;rio Areias

Reputation: 431

There is an error in your Regex. You are matching the term instead to match the whole word. Try this:

regex = new RegExp('\\S*' + term + '\\S*', 'gi');

This regex will match everything around the word that are not spaces.

Upvotes: 1

Related Questions