How can I choose a select option in jQuery as though it were clicked with the mouse?
I am building a search tool with various select drop downs that populate with options via AJAX. The possible options populated are based on the the option chosen in the preceding select drop down. For the purpose of this tool, I want to have the first select box hidden but still need to select an option in that box so that it triggers the AJAX call on the following box, something that is supposed to happen as the result of an "onchange" event.
I've tried all kinds of different code to simulate a mouse click selection of a particular option but, while I can get the option selected, it still isn't triggering the event properly to set off the AJAX call in the following select. This is as far as I've gotten:
From everything I've read, that should set the option value and trigger a change event much like clicking the option. Still, this isn't working. Thanks!
You only have to use val(), like any other field...
We also use change() to call associated events.
Instead of setting the value of the select, set the selected property of the given option, and then trigger a change.
$("option[value='the-value']").prop('selected', true); $("#form select:first").change();