Check Or Uncheck All Items In A Checklist With JavaScript

6th May 2008 - 2 minutes read time

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.

  1. function check_uncheck(truefalse){
  2. var boxes = document.forms[0].chkboxarray.length;
  3. var form = document.getElementById('checkForm');
  4. for(var i=0;i < boxes;i++){
  5. if (truefalse) {
  6. form.chkboxarray[i].checked=true;
  7. } else {
  8. form.chkboxarray[i].checked=false;
  9. }
  10. }
  11. }

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.

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

 

Comments

Permalink

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

bintang (Thu, 03/31/2011 - 07:02)

Add new comment

The content of this field is kept private and will not be shown publicly.