Check Or Uncheck All Items In A Checklist With JavaScript

If you have lots of check boxes in a row a handy little usability trick is to allow a user to click on a button and check all of the checkboxes at once. The following function will either check or uncheck all of the check boxes in your form.

function check_uncheck(truefalse){
 var boxes = document.forms[0].chkboxarray.length;
 var form = document.getElementById('checkForm');
 for(var i=0;i < boxes;i++){
  if (truefalse) {
   form.chkboxarray[i].checked=true;
  } else {
   form.chkboxarray[i].checked=false;
  }
 }
}

All you need to do is to add two buttons to your form that will allow users to either check or uncheck the boxes on the form. The function takes a single parameter, which is what to set the value of the check boxes to, so one button is needed to set them to checked and one to unchecked.

<form name="checkForm" id="checkForm">
<input type="checkbox" name="chkboxarray" value="1" /><br />
<input type="checkbox" name="chkboxarray" value="2" /><br />
<input type="button" name="CheckAll" value="Check All Boxes" onclick="check_uncheck(true)" />
<input type="button" name="UncheckAll" value="Uncheck All Boxes" onclick="check_uncheck(false)" />
</form>

 

Comments

I think there're different parameter between check_uncheck(true, 3) and check_uncheck(truefalse)

Permalink

Yup, quite right. I have corrected the code.

Name
Philip Norton
Permalink

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
9 + 2 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.