最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeError: Cannot set property 'checked' of null for CheckBox - Stack Overflow

programmeradmin0浏览0评论
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+'">&nbsp;</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+'">&nbsp;</label>';
Share Improve this question asked Aug 25, 2017 at 2:55 kuhandran samudra pandiyankuhandran samudra pandiyan 731 gold badge2 silver badges9 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

There could be 2 possible problems.

  1. There is no checkbox with the id as cbox0. Hence, getElementById returns null, leading to your error
  2. 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.

发布评论

评论列表(0)

  1. 暂无评论