JAVASCRIPT

 Home  Computers & Internet  Web Programming JAVASCRIPT
What is Javascript?
Javascript Placement
Syntax
Reserved Words
Variables
Data Types
Escaping Characters
Concatenation
Arithmetic Operators
Assignment Operators
Comparison Operators
Boolean Operators
Conditional Operator
If Statements
Else If Statements
If Else Statements
Switch Statements
While Loops
For Loops
Do While Loops
Break Statement
Continue Statement
prompt()
alert()
Date()
Event Handlers
String Object Methods
Math Object Methods
Window Object Methods

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?

Select All

Romance
Horror
Action
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>

Home | Privacy Policy | Terms Of Use | Contact Us