View Full Version : Check all Checkboxes

Cloud Ghost
12-20-2011, 03:45 AM
Hello, today I am trying to allow a user to easily uncheck/check all checkboxes in a form by checking or unchecking a checkbox.

The checkboxes would be in a form like so:

<form action="" method="post">
<input type="checkbox" name="checked[]" value="1">
<input type="checkbox" name="checked[]" value="2">
<input type="checkbox" name="checked[]" value="3">
<input type="checkbox" name="checked[]" value="4">

I use an event handler to call a function:

<input type="checkbox" name="checkall" onchange="checkall('checked[]', this.checked)">

And here is the function:

function checkall(box_name, current_state) {
all = document.getElementsByName(box_name);
action = (current_state == "checked") ? "false" : "true";
for (i = 0; i < all.length; i++) {

The event handler should pass the name of the checkboxes and whether the "check all" checkbox is currently checked or not to the checkall() function. Nothing happens when I check/uncheck the "check all" function. Help?

12-20-2011, 04:18 AM
Try this:

<form action="" method="post">
<div id="checkboxContainer">
<input type="checkbox" name="blah[]" value="1" />
<input type="checkbox" name="blah[]" value="2" />
<input type="checkbox" name="blah[]" value="3" />
<input type="checkbox" name="blah[]" value="4" />

<p>Check all <input type="checkbox" name="checkall" onchange="checkall('checkboxContainer', this.checked);"></p>

<script type="text/javascript">
function checkall(containerID, state)
var all = document.getElementById(containerID).getElementsByTagName('input');
for (var i=0; i<all.length; i++)
all[i].checked = state;

Also, you shouldn't name a checkbox element "checked". This is a reserved word in JS, and could cause problems in your code. I took the liberty of changing it.

12-20-2011, 04:25 AM
<input type="checkbox" name="checkall" onclick="checkall('checked[]', this.checked)">

(IE doesn't seem to like using onchange for a checkbox)