简体   繁体   中英

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 (eg make bold ) the the portion of the result that matches the text they've typed.

eg 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?

This functionality is not built in, but you can easily accomplish it by "monkey-patching" the _renderItem function of the autocomplete widget. Take a look at this question for exactly what you want:

jQueryUI: how can I custom-format the Autocomplete plug-in results?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM