Wednesday, 26 August 2015

Check all checkbox using a single checkbox in JavaScript

A simple pure Javascript demo with code is demonstrating, how to check all checkbox on checking a single checkbox.


Demo

Check this checkbox to try out.




Code

<input id="all" onclick="SelectAllCheckboxes();" type="checkbox" /> 

<br />
<input name="checkGroup" type="checkbox" />
<input name="checkGroup" type="checkbox" />
<input name="checkGroup" type="checkbox" />
<input name="checkGroup" type="checkbox" />
<input name="checkGroup" type="checkbox" />
<input name="checkGroup" type="checkbox" />
<input name="checkGroup" type="checkbox" />

<script>

function SelectAllCheckboxes()
{
var chk=document.getElementsByName("checkGroup");
if(document.getElementById("all").checked==true )
{
for (i = 0; i < chk.length; i++)
chk[i].checked = true   ;
}
else 
{
for (i = 0; i < chk.length; i++)
chk[i].checked = false    ;
}
return false;
}


</script>