[英]Call onchange function when a checkbox is checked on unchecked from code
I'm using pure javascript. 我正在使用纯JavaScript。 There's a checkbox with a function attached to it when "onchange" event occurs.
当发生“ onchange”事件时,会有一个复选框附加了功能。
I want to call that function, when I check and uncheck it from the javascript code. 当我从javascript代码中选中和取消选中该函数时,我想调用该函数。
It gets checked and unchecked but that function is not called unless I do it from manually by keyboard arrow keys. 它会被选中和取消选中,但是除非我通过键盘上的箭头键手动进行操作,否则不会调用该函数。
Is there any way to make that function get called ? 有什么方法可以使该函数被调用吗?
HTML DOM : HTML DOM:
<input type="checkbox" onchange="hello();" id="myCheckBox">
Javascript: Javascript:
document.getElementById("myCheckBox").checked = true;
The 'onchange' event is for use in text boxes and selection lists, try the 'onclick' event. “ onchange”事件用于文本框和选择列表,请尝试“ onclick”事件。
To fire an event from code you might find this useful: 要从代码中触发事件,您可能会发现这很有用:
Invoke the handler function when your JavaScript code changes the state of the checkbox elements. 当您的JavaScript代码更改复选框元素的状态时,调用处理程序函数。
function toggle() { document.getElementById("myCheckBox").checked = !document.getElementById("myCheckBox").checked; hello(); //invoke the function here! } function hello() { alert(document.getElementById("myCheckBox").checked) }
<input type="checkbox" onchange="hello();" id="myCheckBox"> <button onclick='toggle()'>Toggle</button>
Use this: 用这个:
HTMLInputElement.prototype.check = function() {
if (this.checked !== null) {
this.checked = true;
this.onchange();
}
};
HTMLInputElement.prototype.uncheck = function() {
if (this.checked !== null) {
this.checked = false;
this.onchange();
}
};
document.getElementById("myCheckBox").check();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.