onChange event with javascript modifications of checkbox

Viewed 249

I tried to check a checkbox with js and detect the change, but the event onchange not detect the change, while that is visually changing. (sorry for by bad english, i'm french) Here is an example:

document.querySelector("#checkbox").onchange = (e) => {
  let checked = e.target.checked;
  if (checked) {
    console.log("checked !");
  } else {
    console.log("unchecked...");
  }
}

document.querySelector("#buttonOn").onclick = (e) => {
  document.querySelector("#checkbox").checked = true;
}
document.querySelector("#buttonOff").onclick = (e) => {
  document.querySelector("#checkbox").checked = false;
}
<button id="buttonOn">On</button>
<button id="buttonOff">Off</button>
<input type="checkbox" name="" id="checkbox">

1 Answers

You need to trigger event while you click buttons

document.querySelector("#checkbox").onchange = (e) => {
  let checked = e.target.checked;
  if (checked) {
    console.log("checked !");
  } else {
    console.log("unchecked...");
  }
}

// Create new change event
var event = new Event('change');

document.querySelector("#buttonOn").onclick = (e) => {
  document.querySelector("#checkbox").checked = true;
  // Trigger onchange
  document.querySelector("#checkbox").dispatchEvent(event);
}
document.querySelector("#buttonOff").onclick = (e) => {
  document.querySelector("#checkbox").checked = false;
  // Trigger onchange
  document.querySelector("#checkbox").dispatchEvent(event);
}
<button id="buttonOn">On</button>
<button id="buttonOff">Off</button>
<input type="checkbox" name="" id="checkbox">

Related