Why onchange function not called when checkbox changed using checked property

你。 提交于 2021-02-05 08:36:00

问题


Checkbox is handled using another button.

  1. If I directly click on checkbox then the onchange triggers.

  2. But when I change the check box using button, onchange(i.e. show() method) is not called.

var checkbox=document.getElementById("x");
var button=document.getElementById("y");

button.addEventListener("click",function(){
checkbox.checked== true
?checkbox.checked=false
:checkbox.checked=true;

})


var show=function(){
window.alert("onchange called");
}
<input type='checkbox' name='xyz' id='x' onchange="show()">

<br>

<button id='y'>Toggle Checkbox</button>

How to call show() method if button is clicked.


回答1:


Setting the checked property of a checkbox doesn't trigger a change event from that checkbox. You will have to dispatch it yourself:

y.addEventListener('click', (e) => {
  // toggle the checkbox
  x.checked = !x.checked;
  // and manually dispatch a change event on the checkbox
  let change = new Event('change');
  x.dispatchEvent(change);
})

x.addEventListener('change', (e) => {
  console.log(x.checked);
})
<input type='checkbox' name='xyz' id='x' />

<br>

<button id='y'>Toggle Checkbox</button>


来源:https://stackoverflow.com/questions/52481530/why-onchange-function-not-called-when-checkbox-changed-using-checked-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!