Home  >  Article  >  Web Front-end  >  How to Customize Autocomplete Plugin Result Formatting in jQuery UI?

How to Customize Autocomplete Plugin Result Formatting in jQuery UI?

Barbara Streisand
Barbara StreisandOriginal
2024-10-21 08:07:30776browse

How to Customize Autocomplete Plugin Result Formatting in jQuery UI?

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;'>" + 
          "$&amp;" + 
          "</span>");

Limitations

While this method allows you to highlight the search term in the drop-down results, it also has limitations:

  • Every autocomplete widget on the page will be affected.
  • The term is highlighted with inline styling instead of a CSS class.

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!

Statement:
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