Customizing Autocomplete Plug-in Results
The jQuery UI Autocomplete plug-in offers a wide range of features, but it may not always meet your precise formatting requirements. If you need to highlight search character sequences within dropdown results, here's how you can leverage the plug-in's flexibility:
Monkey-Patching the Autocomplete Plug-in
The key to customizing the results is to replace the default _renderItem function that generates the dropdown list items. You can do this through a technique called "monkey-patching." By defining a new _renderItem function, you can render the results in the desired format.
Implementation
The following code sample provides an enhanced version of the _renderItem function that formats matching character sequences with bold text:
$.ui.autocomplete.prototype._renderItem = function (ul, item) { var re = new RegExp("^" + this.term); var t = item.label.replace(re, "<span style='font-weight:bold'>$&</span>"); return $( "<li></li>" ) .data("item.autocomplete", item) .append( "<a>" + t + "</a>" ) .appendTo(ul); };
Integrating into Your Code
Call the monkeyPatchAutocomplete function within the $(document).ready(...) block once to enable the custom formatting:
monkeyPatchAutocomplete();
Limitations
While this technique provides basic functionality, it has a few limitations:
Preserving Case
To maintain the original case of the search characters instead of matching the typed characters, use "$&" instead of "this.term" in the code:
var t = item.label.replace(re, "<span style='font-weight:bold'>$&</span>");
The above is the detailed content of How to Highlight Search Terms in jQuery UI Autocomplete Dropdowns?. For more information, please follow other related articles on the PHP Chinese website!