How to highlight jquery ui autocomplete words

I am using this script http://jqueryui.com/demos/autocomplete/#default with the database. I want to highlight the typed words as follows: www.docs.jquery.com/Plugins/Autocomplete. Please help me.

+4
source share
2 answers

It looks like it works at http://docs.jquery.com/Plugins/Autocomplete has a highlighting method.

You can recreate this by grabbing the regexp by their highlighting method and using it to modify the results that are sent back from your ajax request to your 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 wiser to add a server side <strong> wrapper, as it will most likely already go through each of the results.

+2
source

I had to change the code to allocate a jQuery autocomplete user interface 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 ); }; 
+2
source

Source: https://habr.com/ru/post/1312965/


All Articles