Reputation: 265
<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
Upvotes: 4
Views: 14518
Reputation: 92367
Try
['A','C'].forEach(v=> document.querySelector(`[value=${v}]`).checked=1)
['A','C'].forEach(v=> document.querySelector(`[value=${v}]`).checked=1)
// and her is longer but theoretically more efficient version:
// document.querySelectorAll(['A','C'].map(v=> `[value=${v}]`)+'').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>
Upvotes: 1
Reputation: 21759
You can use
document.querySelectorAll("input[value=A]")[0].checked = true;
document.querySelectorAll("input[value=C]")[0].checked = true;
Upvotes: 0
Reputation: 1
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>
Upvotes: 0
Reputation: 2397
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>
Upvotes: 3
Reputation: 11
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;
Upvotes: 0