It’s a common problem: you have a list of elements on a page and you want yout user to be able to do something to several or all elements at once (delete, move, etc.) so you give each element a checkbox and a “delete selected” button (or similar :~). Everything is cool but then you figure it would be nice to have a “select all” resp. “unselect all” box too, so help avoid “click orgies”. So in the page you generate something like this:
<input type=’checkbox’ id=’sel1′ value=’xxx’ name=’sel[]‘ /> xxx<input type=’checkbox’ id=’sel2′ value=’yyy’ name=’sel[]‘ />
yyy<input type=’checkbox’ id=’sel3′ value=’zzz’ name=’sel[]‘ />
zzz<input type=’checkbox’ id=’selAll’ value=” name=’selAll’ onClick=’selectAll(this.checked, \”sel[]\”)’ />
(un)select all
There are several ways of doing this, but I like my solution, just because its mine its short and effective:
function selectAll(state, name) {
..boxes = document.getElementsByName(name);
..boxCnt = boxes.length;
..for (i=0; i<boxCnt; i++) {
....boxes[i].checked = state;
..}
}
That’s it!