The logic in the change()
event handler is not being run when the value is set by val()
, but it does run when user selects a value with their mouse. Why is this?
<select id="single">
<option>Single</option>
<option>Single2</option>
</select>
<script>
$(function() {
$(":input#single").change(function() {
/* Logic here does not execute when val() is used */
});
});
$("#single").val("Single2");
</script>
To make it easier add a custom function and call it when ever you want that changing the value also trigger change
and
Or you can override the val function to always call the change when the val is called
Sample at http://jsfiddle.net/r60bfkub/
If you've just added the select option to a form and you wish to trigger the change event, I've found a setTimeout is required otherwise jQuery doesn't pick up the newly added select box:
As far as I can read in API's. The event is only fired when the user clicks on an option.
http://api.jquery.com/change/
Adding this piece of code after the val() seems to work:
In case you don't want to mix up with default change event you can provide your custom event
to trigger the event on value set, you can do
This worked for my script. I have 3 combos & bind with chainSelect event, I need to pass 3 values by url & default select all drop down. I used this
And the first event worked.