Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 989
DaveDev Avatar asked Aug 22 '11 11:08

DaveDev


1 Answers

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.

like image 177
Zeeshan Eqbal Avatar answered Oct 22 '22 07:10

Zeeshan Eqbal