JAVASCRIPT CHECK ONE CHECK ALL CHECKBOXES
This tutorial and sample script shows you how to create a check one check all feature for your checkboxes. In the
demo below, if you check the first checkbox Select All, all other checkboxes will get checked. If you uncheck this
checkbox, all other checkboxes will uncheck.
DEMO: Check One Check All Checkboxes
What type of movies do you like?
The first thing we do is create a simple form called demo as below:
<form name="demo">
<input type="checkbox" name="master" value="">Select All
<input type="checkbox" name="choices" value="Romance">Romance
<input type="checkbox" name="choices" value="Horror">Horror
<input type="checkbox" name="choices" value="Action">Action
</form>
We then create a function called checkAll which we place in between the <head> and </head> section of
our page.
<script type="text/javascript">
function checkAll()
{
We then use an if statement to say that if the first checkbox (Select All)
is checked then all checkboxes in the
for loop must be checked.
if(document.demo.master.checked== true)
{
for(var i=0; i < document.demo.choices.length; i++)
{
document.demo.choices[i].checked=true;
}
}
We then say if not, then all checkboxes in the for loop must be unchecked.
else
{
for(var i=0; i < document.demo.choices.length; i++)
{
document.demo.choices[i].checked=false;
}
}
}
</script>
The full function script is:
<script type="text/javascript">
function checkAll()
{
if(document.demo.master.checked== true)
{
for(var i=0; i < document.demo.choices.length; i++)
{
document.demo.choices[i].checked=true;
}
}
else
{
for(var i=0; i < document.demo.choices.length; i++)
{
document.demo.choices[i].checked=false;
}
}
}
</script>
Now all that is left to do is the add the call to function in our form we created (add text in red) as
below:
<form name="demo">
<input type="checkbox" name="master" onclick="checkAll();" value="">Select All
<input type="checkbox" name="choices" value="Romance">Romance
<input type="checkbox" name="choices" value="Horror">Horror
<input type="checkbox" name="choices" value="Action">Action
</form>
|