Check all checkbox

L

limbo2u

I'm using the following code for a checkbox that when clicked, either
checks or unchecks a group of checkboxes on a form. The code works
fine, except when there is only one checkbox in the group in which case
the check all checkbox doesn't work at all.

The code working with three checkboxes in a group is as follows, but
remove two of the three and you will see the code stops working:

<script language="javascript" type="text/javascript">
function checkAll( control, cbGroupName )
{
var cbGroup = control.form.elements[cbGroupName], i = 0, cb;
while( cb = cbGroup[i++] )
{
cb.checked = control.checked;
}
}
</script>

<form>
Check all
<input type="checkbox" onclick="checkAll( this,'select[]' );" >
<br><br>
<input type="checkbox" name="select[]" value="234">
<input type="checkbox" name="select[]" value="235">
<input type="checkbox" name="select[]" value="236">
</form>


If anyone can offer some insight into what is causing the problem I
would be very grateful.

Limbo
 
R

RobG

I'm using the following code for a checkbox that when clicked, either
checks or unchecks a group of checkboxes on a form. The code works
fine, except when there is only one checkbox in the group in which case
the check all checkbox doesn't work at all.

The code working with three checkboxes in a group is as follows, but
remove two of the three and you will see the code stops working:

<script language="javascript" type="text/javascript">

Language is deprecated.

function checkAll( control, cbGroupName )
{
var cbGroup = control.form.elements[cbGroupName], i = 0, cb;
while( cb = cbGroup[i++] )

When there is only one checkbox, cbGroup is not a collection and there
is no cbGroup.
{
cb.checked = control.checked;
}
}
</script>

<form>
Check all
<input type="checkbox" onclick="checkAll( this,'select[]' );" >
<br><br>
<input type="checkbox" name="select[]" value="234">
<input type="checkbox" name="select[]" value="235">
<input type="checkbox" name="select[]" value="236">
</form>


If anyone can offer some insight into what is causing the problem I
would be very grateful.

Here's a modified version:

function checkAll( control, cbGroupName )
{
var cbGroup = control.form.elements[cbGroupName],
i = cbGroup.length,
cb;
if ('number' == typeof i){
while( cb = cbGroup[i++] ) {
cb.checked = control.checked;
}
} else {
cbGroup.checked = control.checked;
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top