9

I want to manually select an item in autocomplete and click it given the value.

Following code:

autocompleteitem.autocomplete("option", "autoFocus", true).autocomplete("search", autocompleteitem.val());

autocompleteitem is an object of input that holds the value i want to search for. Now this code successfully selects the first item from drop down but it does not click on it. I do not want to click on it myself i want it to happen somehow in that code.

I tried the following additions to the code above which didnt work:

   .click(), .select(), .trigger('select'), .find('a').click(), .change()

is there any way i can do it?

thanks

please someone help

Giorgi
  • 609
  • 2
  • 15
  • 29

2 Answers2

33

If you look at the way the jQuery team does it in their unit tests for autocomplete, they use something similar to the following code:

    var downKeyEvent = $.Event("keydown");
    downKeyEvent.keyCode = $.ui.keyCode.DOWN;  // event for pressing "down" key

    var enterKeyEvent = $.Event("keydown");
    enterKeyEvent.keyCode = $.ui.keyCode.ENTER;  // event for pressing "enter" key

    $("#autoComplete").val("item"); // enter text to trigger autocomplete
    $("#autoComplete").trigger(downKeyEvent);  // First downkey invokes search
    $("#autoComplete").trigger(downKeyEvent);  // Second downkey highlights first item
    $("#autoComplete").trigger(enterKeyEvent); // Enter key selects highlighted item 

This plunk shows it working

Rune Vejen Petersen
  • 3,201
  • 2
  • 30
  • 46
  • 5
    I would like to note that I was using the combobox jquery plugin (which uses autocomplete) and it required me to fire the DOWN key twice before firing ENTER – Danny Jul 12 '13 at 15:01
  • Of the several questions/answersets on SO on this subject, this is the only one that actually worked for me. Thanks! – B Robster Jul 19 '13 at 20:57
  • 2
    I also found it necessary to fire the DOWN key twice followed by ENTER. – ballPointPenguin Aug 20 '13 at 20:56
  • 1
    The reason the enter key needs to be fired twice is that the UI needs time to update after the keydown has been pressed. Javascript and UI updates cannot run at the same time. Therefore you need to introduce a time delay using the setTimeout() function. – Michael Yagudaev Apr 08 '14 at 21:16
  • I believe you can do it with a delay of 0ms. I often use the defer function in underscore just to make the intent more clear to future maintainers. http://underscorejs.org/#defer – Michael Yagudaev Oct 15 '14 at 20:00
-1

Take a look at this jqFAQ.com topic, this will help you to programatically pick the first matching option for a value and set it into the autocomplete textbox. There are few other autocomplete related faqs too, i think that may be useful for you.

Amar
  • 1,906
  • 2
  • 16
  • 26