Javascript Checkbox Select All

Giving your users a little help

One design practice I try to use on any page I create is that if there are multiple check boxes on a page, you should always give the user the option to select (or deselect) all of them with a single click. Luckily, with javascript, this is quite easy to do.

To create the javascript to check all check boxes on a page, use the following code:

<script type="text/javascript">
function checkAll(field) {
   if (field.CheckAll.checked == true) {
      for (i = 0; i < field.length; i++) {
         if (field[i].name == "Check"){
            field[i].checked = true;
         }
      }
   }
   else {
      for (i = 0; i < field.length; i++) {
         if (field[i].name == "Check"){
            field[i].checked = false;
         }
      }
   }
}
</script>

To use this code, you will need a checkbox on your page. Code for that checkbox is as follows:

<form action="page-to-go-to.asp" method="post" name="FormName">

   <input type="checkbox" name="CheckAll" id="CheckAll" value="1" onClick="checkAll(FormName)">

   <input type="checkbox" name="Check" id="Check1" value="1"> Checkbox #1
   <input type="checkbox" name="Check" id="Check2" value="1"> Checkbox #2
   <input type="checkbox" name="Check" id="Check3" value="1"> Checkbox #3
   <input type="checkbox" name="Check" id="Check4" value="1"> Checkbox #4

</form>

To view a quick demo of this technique, click here External Link

NOTE: The form that you are using must have a name in order for this function to work. In this example, I used the name FormName but you can change this to anything that you want.

NOTE #2: In this example, I am checking the name of the check box in order to see if it should be checked. This allows you to make the function only check the boxes you want it to. If you want the function to check all check boxes on the page, you may remove the lines where it checks the name of the box.

Javascript

Ads