Shaun Mccran

My digital playground

26
A
U
G
2008

JavaScript checkBox checker and unchecker

A few times I've encountered the need to check, or uncheck a large column of records in a data display. Say you have one hundred records returned from a query, instead of having a user check each one, simply give them a button that allows them to check or uncheck a whole column in one go!

Place this inside a 'script' tag on your page header.

view plain print about
1function checkAll(field1)
2{
3for (i = 0; i < field1.length; i++)
4    field1[i].checked = true ;
5}
6
7function uncheckAll(field1)
8{
9for (i = 0; i < field1.length; i++)
10    field1[i].checked = false ;
11}
12//

Then call the JavaScript function with an event, such as a button click.

view plain print about
1<input type="checkbox" name="approve" value="1">value<br>
2<input type="checkbox" name="approve" value="2">value<br>
3<input type="checkbox" name="approve" value="3">value<br>
4<input type="checkbox" name="approve" value="4">value<br>
5<input type="checkbox" name="approve" value="5">value<br>
6
7<input type="button" name="CheckAll" value="Check All"
8onClick="checkAll(document.form.approve)">

9<input type="button" name="UnCheckAll" value="Uncheck All"
10onClick="uncheckAll(document.form.approve)">

you can also have the functions reference each other, so fpr instance.

view plain print about
1// checks all field
2function checkAll(field1, field2)
3    {
4        for (i = 0; i < field1.length; i++)
5            field1[i].checked = true ;
6
7// call the uncheck method        
8uncheckAll(field2);
9    
10    }
11
12<input type="button" name="CheckAll" value="Check All"
13onClick="checkAll(document.form.approve, document.form.decline)">

In this way you can have the form automatically check and uncheck whole collections of check boxes, with just one click.

TweetBacks
Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
Back to top