I'm confused on how JavaScript handles Change Events
and am looking for some insight.
Let's say we have two HTML controls; a Checkbox and a Button and I want to use JS to display a message that says how many times the Checkbox has changed from checked
to not-checked
.
<input type="checkbox" id="cb" />
<button id="btn">Change Checkbox</button>
<div id="msg"></div>
The JS can look something like this:
var count = 0;
var cb = document.getElementById("cb");
var btn = document.getElementById("btn");
var msg = document.getElementById("msg");
cb.addEventListener("change", cb_onChange);
btn.addEventListener("click", btn_onClick);
// Change the state of the Checkbox when user clicks the Button
function btn_onClick() {
cb.checked = !cb.checked;
}
// The state of the Checkbox has changed, so increment the change count and display it
function cb_onChange() {
msg.innerHTML = "Checkbox changed " + count+++" times";
}
Test it out here http://jsfiddle.net/26RWh/
Notice that the OnChange
event of the Checkbox
is NOT dispatched when the Checkbox
is programmatically set at cb.checked = !cb.checked
. - i.e. The cb_onChange
listener is only executed if/when the user manually clicks the Checkbox.
How come the OnChange
event isn't fired when I change the state in code?