JavaScript check multiple checkbox

China☆狼群 提交于 2020-01-13 13:45:33

问题


        <input type="checkbox" name="name[]" value="A">A</input>
        <input type="checkbox" name="name[]" value="C">C</input>
        <input type="checkbox" name="name[]" value="D">D</input>
        <input type="checkbox" name="name[]" value="E">E</input>

I have value A and C, how to use javascript make A & C checked


回答1:


This should work for you.

var myNodeList = document.querySelectorAll("input[value=A], input[value=C]");
for (i = 0; i <	myNodeList.length; i++) {
   	myNodeList[i].checked = true;
}
<input type="checkbox" name="name[]" value="A">A</input>
<input type="checkbox" name="name[]" value="C">C</input>
<input type="checkbox" name="name[]" value="D">D</input>
<input type="checkbox" name="name[]" value="E">E</input>



回答2:


Why not just give the checkbox an id like:

   <input type="checkbox" name="name[]" value="A" id="checkA">A</input>

then use the following javascript:

document.getElementById("checkA").checked = true;



回答3:


You have to assign a id to the input box first then you can call javascript by using that id.

  <html>
    <script type="text/javascript">
    function setValue()
    {
       document.getElementById("A").checked = true;
       document.getElementById("C").checked = true;
    }
    </script>
    <body>
       <input id="A" type="checkbox" name="name[]" value="A">A</input>
       <input id="B" type="checkbox" name="name[]" value="C">C</input>
       <input id="C" type="checkbox" name="name[]" value="D">D</input>
       <input id="D" type="checkbox" name="name[]" value="E">E</input>
       <br/><br/>
       <button onClick="setValue()"> Set Value </button>
    </body>
  </html>



回答4:


You can use

document.querySelectorAll("input[value=A]")[0].checked = true;
document.querySelectorAll("input[value=C]")[0].checked = true;



回答5:


Try

document.querySelectorAll('[value=A], [value=C]').forEach(c => c.checked=1)

document.querySelectorAll('[value=A], [value=C]').forEach(c => c.checked=1)
<input type="checkbox" name="name[]" value="A">A</input>
<input type="checkbox" name="name[]" value="C">C</input>
<input type="checkbox" name="name[]" value="D">D</input>
<input type="checkbox" name="name[]" value="E">E</input>


来源:https://stackoverflow.com/questions/31032777/javascript-check-multiple-checkbox

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