How highlight words jquery ui autocomplete
i'm using this script http://jqueryui.com/demos/autocomplete/#default with database. i want to highlight typed words like this: www.docs.jquery.com/Plu开发者_开发技巧gins/Autocomplete. Please help me.
Looks like what is running on http://docs.jquery.com/Plugins/Autocomplete has a highlight method.
You can recreate this by grabbing the regex their highlight method and using it to modify your results that get sent back from your ajax request to you database:
$("#example").autocomplete({
source: function(request, response) {
$.ajax({
url: "search.php",
dataType: "json",
data: request,
success: function( data ) {
var regex = new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + request.term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi");
var result = $.map(data, function(value){
return value.replace(regex, "<strong>$1</strong>");
});
response( result );
}
});
}
});
It would probably be smarter to add the <strong>
wrap on the server side since it will most likely already be looping through each on of the results.
I had to modify the code according to this Highlight jQuery UI autocomplete to make it work
$("#searchBox").autocomplete({
source: function(request, response) {
$.ajax({
url: "search.php",
dataType: "json",
data: request,
success: function( data ) {
var escapedTerm=request.term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1");
var regex = new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + escapedTerm + ")(?![^<>]*>)(?![^&;]+;)", "gi");
var result = $.map(data, function(value){
//console.log(value);
value.label=value.label.replace(regex, "<span class='highlight'>$1</span>");
return value;
});
response(result);
}
});
},
minLength: 3
})
.data('autocomplete')._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( '<a>' + item.label + '</a>' )
.appendTo( ul );
};
精彩评论