17

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?

Flo Edelmann
  • 2,573
  • 1
  • 20
  • 33
DaveDev
  • 41,155
  • 72
  • 223
  • 385
  • 1
    Which autocomplete - the one in jQuery UI, or one of the other implementations? I think the (deprecated) [bassistance.de autocomplete](http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/) does this already, for example, but the APIs are different to plug them into your page. – Rup Aug 22 '11 at 11:18
  • @Rup: this one: http://docs.jquery.com/UI/Autocomplete – DaveDev Aug 22 '11 at 11:24
  • Check this out: https://stackoverflow.com/questions/9887032/how-to-highlight-input-words-in-autocomplete-jquery-ui – Mircea Slimu Jan 08 '20 at 21:59

1 Answers1

2

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.

Zeeshan Eqbal
  • 245
  • 2
  • 11