Customizing Autocomplete Plug-in Results
Q: Can I Highlight Search Terms in Autocomplete Drop-Down Results?
Yes, you can customize the format of Autocomplete plug-in results to highlight searched characters.
A: Monkey-Patching the Autocomplete Widget
To achieve this effect, utilize monkey-patching, a technique where an internal function in a library is redefined. In the Autocomplete widget (version 1.8rc3 of jQuery UI), the _renderItem function is responsible for creating the drop-down results. Here's how to redefine it:
function monkeyPatchAutocomplete() { 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 ); }
B: Preserving Case with "$&
To preserve the case of the matched strings, replace this.term with $& in the replace function:
var t = item.label.replace(re, "<span style='font-weight:bold;color:Blue;'>" + "$&" + "</span>");
C: Limitations
This hack has the following limitations:
D: Applying Changes to Specific Instances
If you need to modify only one Autocomplete instance, refer to the following question: How to patch just one instance of Autocomplete on a page?
The above is the detailed content of How to Highlight Search Terms in jQuery UI Autocomplete Results?. For more information, please follow other related articles on the PHP Chinese website!