Home > Web Front-end > JS Tutorial > body text

How to Highlight Search Terms in jQuery UI Autocomplete Dropdowns?

Barbara Streisand
Release: 2024-10-21 08:03:29
Original
161 people have browsed it

How to Highlight Search Terms in jQuery UI Autocomplete Dropdowns?

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);
};
Copy after login

Integrating into Your Code

Call the monkeyPatchAutocomplete function within the $(document).ready(...) block once to enable the custom formatting:

monkeyPatchAutocomplete();
Copy after login

Limitations

While this technique provides basic functionality, it has a few limitations:

  • It creates a separate regexp object for each item, which could be optimized for efficiency.
  • The formatting uses inline styles, which may affect consistency across multiple autocomplete widgets on the same page.

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>");
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!