Home > Web Front-end > JS Tutorial > body text

How to Customize Autocomplete Plugin Display with Bold Match Highlight?

Barbara Streisand
Release: 2024-10-21 07:58:29
Original
734 people have browsed it

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>
Copy after login

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

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

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!