[英]Why onchange function not called when checkbox changed using checked property
Checkbox is handled using another button. 使用另一个按钮处理复选框。
If I directly click on checkbox then the onchange triggers. 如果我直接单击复选框,则会触发onchange。
But when I change the check box using button, onchange(ie show() method) is not called. 但是,当我使用按钮更改复选框时,不会调用onchange(即show()方法)。
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. 如果单击按钮,如何调用
show()
方法。
Setting the checked
property of a checkbox doesn't trigger a change
event from that checkbox. 设置复选框的
checked
属性不会触发该复选框的change
事件。 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.