admin 管理员组文章数量: 1086019
document.getElementById("cbox0").checked = true;
I am using this statement to auto check a checkbox but i get TypeError: Cannot set property 'checked' of null for CheckBox this error. I have tried to use if statement to check if its not a null but it also give me the same error.
jsp+='<input id="cbox'+index+'" type="checkbox" name="pare" value="'+rightCard.oid+'" onchange="myFunction('+index+')"><label for="cboxCard'+index+'"> </label>';
document.getElementById("cbox0").checked = true;
I am using this statement to auto check a checkbox but i get TypeError: Cannot set property 'checked' of null for CheckBox this error. I have tried to use if statement to check if its not a null but it also give me the same error.
jsp+='<input id="cbox'+index+'" type="checkbox" name="pare" value="'+rightCard.oid+'" onchange="myFunction('+index+')"><label for="cboxCard'+index+'"> </label>';
Share
Improve this question
asked Aug 25, 2017 at 2:55
kuhandran samudra pandiyankuhandran samudra pandiyan
731 gold badge2 silver badges9 bronze badges
2 Answers
Reset to default 4There could be 2 possible problems.
- There is no checkbox with the
id
ascbox0
. Hence,getElementById
returnsnull
, leading to your error - Your JavaScript is executed before your checkbox is loaded into the DOM. You can solve this by wrapping your code inside a
DOMContentLoaded
event listener, like this
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("cbox0").checked = true;
});
<input id="cbox0" type="checkbox" name="pare" value="test">
Note that the snippet above works even without the event listener on StackOverflow. That's probably because StackOverflow's snippet runs it's JavaScript similar to what I've written.
wrap your code within an onload
event.
本文标签: javascriptTypeError Cannot set property 39checked39 of null for CheckBoxStack Overflow
版权声明:本文标题:javascript - TypeError: Cannot set property 'checked' of null for CheckBox - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744076582a2529462.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论