(Un)check all boxes in fieldsets

set zero
set one
set two
Javascript
function checkAll(ca) {
var fs=ca.id.split('-')[1];
var cboxes=document.getElementById('fs-'+fs).getElementsByTagName('input');
for (j=0; j<cboxes.length; j++) {
cboxes[j].checked=((ca.checked==true)? true : false);
}
}
function initCheckAll() {
var fsets=document.getElementById('caForm').getElementsByTagName('fieldset');
for (i=0; i<fsets.length; i++) {
document.getElementById('ca-'+i).onclick=function() {checkAll(this)}
}
}
window.onload=initCheckAll;
HTML
<h1>(Un)check all boxes in fieldsets</h1>
<form action="#" id="caForm">
<fieldset id="fs-0">
<legend>set zero</legend>
<label>One: <input type="checkbox"></label>
<label>Two: <input type="checkbox"></label>
<label>Three: <input type="checkbox">
</label>
<label>Check/Uncheck all <input type="checkbox" id="ca-0"></label>
</fieldset>
<fieldset id="fs-1">
<legend>set one</legend>
<label>One: <input type="checkbox"></label>
<label>Two: <input type="checkbox"></label>
<label>Three: <input type="checkbox"></label>
<label>Check/Uncheck all <input type="checkbox" id="ca-1"></label>
</fieldset>
<fieldset id="fs-2">
<legend>set two</legend>
<label>One: <input type="checkbox"></label>
<label>Two: <input type="checkbox"></label>
<label>Three: <input type="checkbox"></label>
<label>Check/Uncheck all <input type="checkbox" id="ca-2"></label>
</fieldset>
</form>
CSS
#caForm label {
display:block;
position:relative;
width:15em;
margin:auto;
}
#caForm label input {
position:absolute;
right:0;
}

Comments

#1
2008-04-02 Melanie says :

I can get it to work in IE but not FF for some strange reason and I have no clue why

#2
2008-04-06 BonRouge says :

Melanie,
It works fine for me on FF.

#3
2008-09-03 Richard of Norway says :

This is brilliant work. Cheers!
I'll test it out and let you know if I have problems in any browsers. I test ie6+, ff2+, opera 9+ and safari.

#4
2008-09-03 NightAvatar says :

Great job. One thing it lacks is to check/uncheck the "check all" box when all other checkboxes in fieldset are checked/unchecked.

#5
2009-06-01 tony weeg says :

i can get this to work just fine in all browsers, but the minute i take the code and put it in my own page its not working in Chrome or Firefox. Works FINE in IE, any ideas?

#6
2009-06-01 BonRouge says :

tony weeg,
Can you show me the page?

Comment form

Please type the word 'brown' here:

BB code available :

  • [b]...[/b] : bold
  • [it]...[/it] : italic
  • [q]...[/q] : quote
  • [c]...[/c] : code
  • [url=...]...[/url] : url