0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jed
  • 10,649
  • 19
  • 81
  • 125
  • Does this answer your question? [Call Javascript onchange event by programmatically changing textbox value](https://stackoverflow.com/questions/735462/call-javascript-onchange-event-by-programmatically-changing-textbox-value) – Brian Tompsett - 汤莱恩 Mar 23 '20 at 08:58

2 Answers2

0

This is the way events on input-elements work in javascript.

If you want the callback to be executet you need to manually fire the change-event on the checkbox.

There are questions about this:

do it in pure JavaScript

and with help of jquery

Community
  • 1
  • 1
phylax
  • 2,034
  • 14
  • 13
0

when the browser identifies a change event in checkbox, it sets the checked propery to !checked and calls the subscribed functions which you can assume happens in one function(f1) and which is called when the event occurs. In this case you are not calling the function f1 but just setting the property.

rohit anand
  • 286
  • 3
  • 5