Home > Web Front-end > JS Tutorial > How to Highlight Search Terms in jQuery UI Autocomplete Results?

How to Highlight Search Terms in jQuery UI Autocomplete Results?

DDD
Release: 2024-10-21 08:05:03
Original
824 people have browsed it

How to Highlight Search Terms in jQuery UI Autocomplete Results?

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

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

C: Limitations

This hack has the following limitations:

  • A new RegExp object is created for each item rendered in the list.
  • No CSS class is used for formatting, so multiple Autocompletes on the same page would have the same styling.

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template