Customizing Autocomplete Plugin Result Formatting
When utilizing the popular jQuery UI Autocomplete plugin, you may encounter the need to highlight specific character sequences in the drop-down results to enhance user experience. This article explains how to achieve this effect.
Monkey-Patching the Autocomplete Widget
To customize the result formatting, you'll need to replace the default _renderItem function of the autocomplete widget. This function is responsible for creating each item in the drop-down list. By overriding it, you can modify the item's appearance to include custom formatting.
Here's an example of such a monkey patch:
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 ); }; }
Call this function once within the $(document).ready(...) event handler to activate the customization.
Handling Case Sensitivity
If you want to preserve the case of the match strings rather than using the case of the typed characters, use this line:
var t = item.label.replace(re,"<span style='font-weight:bold;color:Blue;'>" + "$&" + "</span>");
Limitations
While this method allows you to highlight the search term in the drop-down results, it also has limitations:
Additional Notes
If you need to customize only one specific instance of the Autocomplete widget on a page, you can use a more targeted approach. Refer to the documentation for details.
The above is the detailed content of How to Customize Autocomplete Plugin Result Formatting in jQuery UI?. For more information, please follow other related articles on the PHP Chinese website!