I was looking around to add an event to a checkbox and I would have thought people would use .change
to set up a change event but instead I found that people are using .click
Is there a reason for this? They both seem to work fine both with clicked events and with keyboard changes. Am I missing something?
If you don't believe me then try it out yourself
onchange
in IE only fires when the checkbox loses focus. So if you tab to it, hit space a few times, tab out, you'll only get one onchange
event, but several onclick
events.
Note: this is one of the very, very, very rare times when IE's behavior is correct (according to spec) and other browsers are wrong.
Two reasons why onclick
is preferred over onchange
.
Internet Explorer only fires the onchange event when the checkbox loses the focus (onblur). So onclick
is more of a cross browser solution.
onchange
happens only after the element lose focus.(You wont see a difference since you are calling alert and losing focus on every change). The pseudo code on MDC pretty much explains the element.onchange
implementation.
control.onfocus = focus; control.onblur = blur; function focus () { original_value = control.value; } function blur () { if (control.value != original_value) control.onchange(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With