Reputation: 87
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
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