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:

jQuery('#form select').first().val('the-value').trigger('click').trigger('change');

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!

Answers


You only have to use val(), like any other field...

$("select").val("2").change();

http://jsfiddle.net/Loenix34/3LbjY/

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();

Fiddle Demo


Need Your Help

Can't connect to memcache

php apache caching memcached

I am trying to connect to memcache as they suggest:

JPA2 Criteria - select element which has a collection with another element with specified value

hibernate jpa criteria

There are two classes A and B. Class A has a collection of objects of class B in it. Class B has a field X. I'd like to be able to return list of objects of class A that have in their collections o...