带有javascript修改复选框的onChange事件

时间:2020-08-22 08:49:18

标签: javascript html checkbox dom-events

我试图用js选中一个复选框并检测到更改,但是onchange事件未检测到更改,而这在视觉上已更改。 (对不起,英语不好,我是法国人) 这是一个示例:

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 个答案:

答案 0 :(得分:2)

您需要在单击按钮时触发事件

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">