I am trying to understand why the change event in the following example is not triggered (I\'ll show exactly where).
I have a checkbox, lets call it \'mainCheckbox
In general, the events are only fired in response to user actions, not actions in code. Setting the checked
property on a checkbox does not fire its change
event; the user changing the checkbox's checked state does.
This is also true for when you use code to set the value
of an input
, the selectedIndex
(or value
) of a select
, etc.
It's also true in relation to the submit
events on form
elements: Calling an HTMLFormElement
's submit
function will submit the form without triggering its submit
event. But, if you use jQuery to submit the form (e.g., if you call submit
on a jQuery object wrapped around an HTMLFormElement
), it does trigger its submit
event handlers. This is an unfortunate by-product of jQuery's API design.
If you want to trigger an event, you can do that with jQuery's trigger function. So if it's appropriate, after setting checked
, you could .trigger("change")
. In general I advocate not generating synthetic predefined events like that (instead, just call whatever function you need to call, or use a synthetic custom event), but there are valid use cases.
Onchange event is fired when the element loses focus. Since you are changing the value programmatically, the element you are changing never loses focus. You may wish to check the oninput
event.