Why does the jquery change event not trigger when I set the value of a select using val()?
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>
Solution 1:
Because the change
event requires an actual browser event initiated by the user instead of via javascript code.
Do this instead:
$("#single").val("Single2").trigger('change');
or
$("#single").val("Single2").change();
Solution 2:
I believe you can manually trigger the change event with trigger()
:
$("#single").val("Single2").trigger('change');
Though why it doesn't fire automatically, I have no idea.