When binding to a click event for a checkbox input, the checkbox is already toggled by the time my event handler runs and, more oddly, the toggle is reversed after my event handler runs if I specify event.preventDefault();
<input id="foo" type="checkbox"/>
function clicked(evt) {
alert(document.getElementById('foo').checked);
evt.preventDefault();
}
document.getElementById('foo').addEventListener('click',clicked);
[tested in chrome and firefox]
JSFiddle for that code
The alert will respond "true" (or the opposite state of the checkbox pre-click). After you dismiss the alert, the checkbox toggles back.
So, I guess the questions are,
What is the actual default event being prevented? Am I wrong in assuming my event handler should be running before the state is changed? Is there a way to legitimately intercept a checkbox click?
And why in the world is the preventDefault causing the re-toggling the checkbox?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…