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.

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

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.