Reputation: 116273
I have set up an autocomplete feature for an input box, with jQuery UI's .autocomplete()
.
How can I access the array (or object?) of results that drop-down when I start typing?
I would like to use the results to highlight various other elements on my page.
Upvotes: 3
Views: 1611
Reputation: 126042
There are two ways you can accomplish this.
Use the source
option to define logic for filtering results. This logic would be identical to the widget's source code:
$("#auto").autocomplete({
source: function (request, response) {
var results = $.ui.autocomplete.filter(source, request.term);
$("#results").text(results.join(", "));
response(results);
}
});
Example: http://jsfiddle.net/andrewwhitaker/27S6p/
If you're using a remote datasource, this is easy to integrate into your AJAX response.
If you needed a solution for multiple autocomplete widgets, you could override the _response
function to raise a special event that you can bind to:
var __response = $.ui.autocomplete.prototype._response;
$.ui.autocomplete.prototype._response = function(content) {
__response.apply(this, [content]);
this.element.trigger("autocompletesearchcomplete", [content]);
};
$("#auto").autocomplete({
source: src
}).bind("autocompletesearchcomplete", function (event, results) {
$("#results").text(results.join(", "));
});
Example: http://jsfiddle.net/andrewwhitaker/V9Vun/
I would only use this solution if you have several widgets on the page and you need to do this for all of them.
Neither of them are ideal but should get the results you're looking for.
Upvotes: 3
Reputation: 5644
You can access the options with
$('input[type="text"]').autocomplete({
source: availableTags,
open: function( event, ui ) {
var autocomplete = $( this ).data( "autocomplete" ),
menu = autocomplete.menu;
console.log(menu.element.children());
}
});
menu.element.children()
gives you the HTML List items. You can easily parse them (Strip the HTML) and build an array from that and pass it to your highlight function.
Edit2: The following Edit does not return the expected values.
Edit: Instead of accessing menu.element
, go for console.log(autocomplete.options.source);
Upvotes: 1
Reputation: 69905
Take a look at result
event. I think it will give you the array of objects which it shows in the auto complete.
http://docs.jquery.com/Plugins/Autocomplete/result#handler
Upvotes: 1