How to highlight jQuery Autocomplete results that match the text already typed?

DaveDev picture DaveDev · Aug 22, 2011 · Viewed 31.5k times · Source

I've implemented jQuery Autocomplete for a client. Now they want me to highlight (e.g. make bold) the the portion of the result that matches the text they've typed.

e.g. the user types "something", and the results are as follows:

something a

something b

Another something

Do something else

Is this functionality built into jQuery Autocomplete? If so, what is it?

Or is this something I'll have to implement myself? If so, where do I start with that?

Answer

Zeeshan Eqbal picture Zeeshan Eqbal · Jan 16, 2020

I had the same requirement previously.

Below code may work for you.

"You need to be careful with selectors"

<script>
  $("#input-search-box")
    .autocomplete({
      //your code
    })
    .data("autocomplete")._renderItem = function(ul, item) {
    var items = $("<li></li>").data("ui-autocomplete-item", item);
    //match and key variables highlight the user's typed input rendering in bold blue for dropdown items.
    var match = new RegExp("^" + this.term, "i"); //i makes the regex case insensitive

    //change initial typed characters of all item.label   replace is plain JS
    var key = item.label.replace(
      match,
      '<span class="required-drop">' + this.term + '</span>'
    );

    items.html("<a>" + key + "</a>").append(ul);
  }; 
</script>

Let me know if you need more help to implement this code.