Why does the jquery change event not trigger when I set the value of a select using val()?
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.
Solution 3
Adding this piece of code after the val() seems to work:
$(":input#single").trigger('change');
Solution 4
As far as I can read in API's. The event is only fired when the user clicks on an option.
For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.
Solution 5
To make it easier, add a custom function and call it whenever you want to change the value and also trigger a change:
$.fn.valAndTrigger = function (element) {
return $(this).val(element).trigger('change');
}
and
$("#sample").valAndTrigger("NewValue");
Or you can override the val()
function to always call the change when val()
is called:
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function (value) {
this.trigger("change");
return originalVal.call(this, value);
};
})(jQuery);
Sample at http://jsfiddle.net/r60bfkub/
Comments
-
Eric Belair almost 3 years
The logic in the
change()
event handler is not being run when the value is set byval()
, 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>