Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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??

like image 861
Themos Avatar asked Oct 12 '16 12:10

Themos


2 Answers

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.

like image 182
blgt Avatar answered Nov 01 '22 03:11

blgt


Search

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

& Select

var results = $("#autocomplete-id").data("ui-autocomplete").menu.element.c‌​hildren()
.first().cl‌​ick()
like image 43
Ravi Makwana Avatar answered Nov 01 '22 03:11

Ravi Makwana