Home  >  Article  >  Web Front-end  >  How to Customize Autocomplete Plugin Display with Bold Match Highlight?

How to Customize Autocomplete Plugin Display with Bold Match Highlight?

Barbara Streisand
Barbara StreisandOriginal
2024-10-21 07:58:29831browse

How to Customize Autocomplete Plugin Display with Bold Match Highlight?

Customizing Autocomplete Plugin Results' Display with Bold Match Highlight

In jQuery UI's Autocomplete plugin, highlighting search terms in drop-down results enhances user experience. This article explains how to customize this display to suit specific requirements.

Solution: Monkey-Patching

Monkey-patching, a technique to redefine internal library functions, provides a solution. Overriding the _renderItem function, which generates list items for suggestions, allows for custom rendering.

Here's the monkey-patching code that adds a bold highlight to the matching portion of results:

<code class="javascript">function monkeyPatchAutocomplete() {
  $.ui.autocomplete.prototype._renderItem = function(ul, item) {
    var re = new RegExp("^" + this.term);
    var t = item.label.replace(
      re,
      "<span style='font-weight:bold;color:Blue;'>" +
        this.term +
        "</span>"
    );
    return $(`<li></li>`)
      .data("item.autocomplete", item)
      .append(`<a>` + t + "</a>")
      .appendTo(ul);
  };
}</code>

Call this function in $(document).ready(..):

<code class="javascript">$(document).ready(function() {
  monkeyPatchAutocomplete();
});</code>

Considerations:

This hack approach has some limitations:

  • Regex pattern is created for each rendered item, while it could be reused.
  • Inline style is used instead of CSS class for formatting.

Despite these limitations, the technique effectively highlights matching terms in drop-down results, meeting the desired requirement.

The above is the detailed content of How to Customize Autocomplete Plugin Display with Bold Match Highlight?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn