Jak zaškrtnout skupinu checkboxu?

Na webu je spousta návodů jak zaškrtnout všechny checkboxy ve formuláři, ale pokud chcete zaškrtnout pouze nějakou skupinku, ještě k tomu každou jinak pojmenovanou a ještě k tomu když je jich pokaždý jiné množství, je to trošku oříšek. Naštěstí řešení existuje. Zdrojem je diskuse na codingforums.com a řešení je níže:

<script type="text/javascript">
function checkAll(checkbox, theCommonNodeName) {
theCommonNodeName = theCommonNodeName.toLowerCase();
var theCommonNode = checkbox.parentNode;
while(theCommonNode.nodeName.toLowerCase() != theCommonNodeName && theCommonNode != document) {
theCommonNode = theCommonNode.parentNode;
}

if(theCommonNode.nodeName.toLowerCase() != theCommonNodeName) {
alert("Common parent node could not be found");
return;
}

var inputs = theCommonNode.getElementsByTagName("input");
for(var i=0; inputs[i]; i++) {
if(inputs[i].type == "checkbox") {
inputs[i].checked = checkbox.checked;
}
}
}
</script>
</head>

<body>
<h1>Test 1</h1>
<form name="frmTest1">
Check all in this form:<input type="checkbox" name="chkAll" onclick="checkAll(this, ‘form’);">
<br><br>
checkbox1:<input type="checkbox" name="chk1"><br>
checkbox2:<input type="checkbox" name="chk2"><br>
checkbox3:<input type="checkbox" name="chk3"><br>
</form>
<hr>

<h1>Test 2</h1>
<form name="frmTest2">
<table border="1" cellspacing="1" cellpadding="2">
<tr><td>Check all in this table:<input type="checkbox" name="chkAll" onclick="checkAll(this, ‘table’);"></td></tr>
<tr><td>checkbox1:<input type="checkbox" name="chk1"></td></tr>
<tr><td>checkbox2:<input type="checkbox" name="chk2"></td></tr>
<tr><td>checkbox3:<input type="checkbox" name="chk3"></td></tr>
</table>
</form>
<hr>

<h1>Test 3</h1>
<form name="frmTest3">
<table border="1" cellspacing="1" cellpadding="2">
<tr>
<td>Check all in this row:<input type="checkbox" name="chkAll" onclick="checkAll(this, ‘tr’);"></td>
<td>checkbox1:<input type="checkbox" name="chk1"></td>
<td>checkbox2:<input type="checkbox" name="chk2"></td>
<td>checkbox3:<input type="checkbox" name="chk3"></td>
</tr>
<tr>
<td>Check all in this row:<input type="checkbox" name="chkAll" onclick="checkAll(this, ‘tr’);"></td>
<td>checkbox4:<input type="checkbox" name="chk4"></td>
<td>checkbox5:<input type="checkbox" name="chk5"></td>
<td>checkbox6:<input type="checkbox" name="chk6"></td>
</tr>
</table>
</form>
</body>
</html>
The code should be pretty self-explanatory, the onclick you add to your "check all" checkbox should be:onclick="checkAll(this, ‘the common parent html tag for your checkboxes’);"
eg:
onclick="checkAll(this, ‘tr’);"
or:
onclick="checkAll(this, ‘div’);"
or:
onclick="checkAll(this, ‘table’);"
etc etc

Leave a Reply

Your email address will not be published.