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

2

5

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

Disequilibrium answered 12/10, 2016 at 12:14 Comment(5)
autoFocus:true should do this out of the box. Why doesn't it work for you?Abbreviation
Autofocus just highlights the option, but it doesn't actually trigger the selection function... The reason I would like the selection function to be triggered is because I use it to auto-populate some additional inputs based on the selected option's key value pair!Disequilibrium
Well, you can trigger a click on the first menu item: $("#autocomplete-id").data("ui-autocomplete").menu.element.children().first().click() Are you sure want to do this, though? 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 allAbbreviation
No this is exactly what I needed, thanks! Can you post your comment as an Answer so I can mark it as Correct?Disequilibrium
Sure, will postAbbreviation
A
5

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.

Abbreviation answered 14/10, 2016 at 16:11 Comment(0)
P
2

Search

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

& Select

var results = $("#autocomplete-id").data("ui-autocomplete").menu.element.c‌​hildren()
.first().cl‌​ick()
Purificator answered 18/10, 2019 at 7:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.