I have a form with thousands of checkboxes, and when one is checked, I want to check all the boxes below it. This works:
<html> <body> <form name='myform'> <input type='checkbox' name='box1' onClick='redrawboxes(this);'>1<br> <input type='checkbox' name='box2' onClick='redrawboxes(this);'>2<br> ... </form> </body> </html> <script> function redrawboxes(obj){ //check all boxes below var foundit=false; for (e=0; e<document.myform.elements.length; e++){ if (foundit==false){ //search for checked obj if(obj == document.myform.elements[e]){ foundit=true; } }else{ //continuing below checked box if(obj.checked){ //are we checking or unchecking document.myform.elements[e].checked = true; }else{ document.myform.elements[e].checked = false; } } } } </script>
but for more than a few thousand boxes, IE is unacceptably slow. (Firefox works fine.) Is there a better way to find the original box besides iterating through the whole list?
Both of the jQuery suggestions are pretty good. For DOM wrangling like this, you’re really better off using a good library.
And the comment about the dubious wisdom of putting thousands of checkboxes on a form is pretty good as well…
But, on the off-chance that you do have a good reason for doing this, and you can’t use jQuery or similar, here’s a fast, straight JS method:
tested in FF3, FF3.1, IE6, Chrome 1, Chromium 2