I’m using the jQuery UI Autocomplete plug-in. Is there a way to highlight search character sequence in drop-down results?
For example, if I have “foo bar” as data and I type "foo" I’ll get “foo bar” in the drop-down, like this:
I’m using the jQuery UI Autocomplete plug-in. Is there a way to highlight search character sequence in drop-down results?
For example, if I have “foo bar” as data and I type "foo" I’ll get “foo bar” in the drop-down, like this:
jQueryUI 1.9.0 changes how _renderItem works.
The code below takes this change into consideration and also shows how I was doing highlight matching using Jörn Zaefferer's jQuery Autocomplete plugin. It will highlight all individual terms in the overall search term.
Since moving to using Knockout and jqAuto I found this a much easier way of styling the results.
To support multiple values, just simply add following function:
Here is my version:
Highlight matched text example
Yes, you can if you monkey-patch autocomplete.
In the autocomplete widget included in v1.8rc3 of jQuery UI, the popup of suggestions is created in the _renderMenu function of the autocomplete widget. This function is defined like this:
The _renderItem function is defined like this:
So what you need to do is replace that _renderItem fn with your own creation that produces the desired effect. This technique, redefining an internal function in a library, I have come to learn is called monkey-patching. Here's how I did it:
Call that function once in
$(document).ready(...)
.Now, this is a hack, because:
there's a regexp obj created for every item rendered in the list. That regexp obj ought to be re-used for all items.
there's no css class used for the formatting of the completed part. It's an inline style.
This means if you had multiple autocompletes on the same page, they'd all get the same treatment. A css style would solve that.
...but it illustrates the main technique, and it works for your basic requirements.
updated working example: http://output.jsbin.com/qixaxinuhe
To preserve the case of the match strings, as opposed to using the case of the typed characters, use this line:
In other words, starting from the original code above, you just need to replace
this.term
with"$&"
.EDIT
The above changes every autocomplete widget on the page. If you want to change only one, see this question:
How to patch *just one* instance of Autocomplete on a page?
Here is a version that does not require any regular expressions and matches multiple results in the label.
for an even easier way, try this: