Home > Article > Web Front-end > 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:
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!