Themos
Themos

Reputation: 460

jQuery autocomplete programmatically search and SELECT first choice (if any)

This should have been pretty straight-forward, but none of the solutions in StackOverflow doesn't seem to work for me...

Using jQuery 2.1.0, I've set up an autocomplete using an Ajax source, autoFocus: true, and a select: function (event, ui) { ... } to provide me with key/value pair combinations.

As soon as I start typing in the input field, I get the correct options as a DDL, which I can then select using the mouse.

However, I would now like to programmatically trigger the autocomplete search, and then SELECT the first option (if available).

I trigger the search like this:

Preparer.autocomplete('search', LoginName);

The available choices show up correctly, but I can't seem to be able to select the first one programmatically!

I tried calling .select(), I've tried triggering keypress 13 and 9 within the control, and even tried performing the actions within a setTimeout function to make sure that the dialog was rendered correctly!

I even tried setting the option { selectFirst: true }, but still nothing...

Is there something else I could try??

Upvotes: 5

Views: 4463

Answers (2)

Ravi Makwana
Ravi Makwana

Reputation: 2918

Search

$('#autocomplete-id').data("uiAutocomplete").search($("#autocomplete-id").val());

& Select

var results = $("#autocomplete-id").data("ui-autocomplete").menu.element.c‌​hildren()
.first().cl‌​ick()

Upvotes: 2

blgt
blgt

Reputation: 8205

As in the comment above:

You can trigger a click on the first menu item:

$("#autocomplete-id").data("ui-autocomplete").menu.element.c‌​hildren().first().cl‌​ick()

Keep in mind: Triggering a select will also close the menu, which seems counterintuitive. It'd be better to intercept the data in source and trigger your custom callback there, and not bother with select at all.

Upvotes: 5

Related Questions