yes i love technology

JS: Unobtrusive Select All Checkboxes

March 26th, 2007 by Pete

I wrote last week about how I’m trying to improve my JavaScript skills. As a small exercise I have written this function for unobtrusively selecting/deselecting checkboxes in a form.

JAVASCRIPT:
  1. function selectAll(box)
  2. {
  3. // get the elements name
  4. var id = box.id;
  5. var name = /^([a-z]+)(_select_all)$/i.exec(id);
  6.  
  7. name = name[1];
  8.  
  9. re = new RegExp('^'+name+'_[0-9]+$');
  10.  
  11. // get the elements stauts
  12. var state = box.checked;
  13.  
  14. // get the form element, search "up"
  15. var form = box.parentNode;
  16. while(form.nodeName.toLowerCase() != "form")
  17. {
  18. if(!form.parentNode) break;
  19. form = form.parentNode;
  20. }
  21.  
  22. // search through forms children for email_ checkboxes
  23. for (i=0;i<form.elements.length;i++)
  24. {
  25. if (form.elements[i].type=='checkbox')
  26. {
  27. // Find checkbox for each member of the group:
  28. if (re.test(form.elements[i].name))
  29. {
  30. form.elements[i].checked = state;
  31. }
  32. }
  33. }
  34. }
  35.  
  36.  
  37.  
  38. // onload stuff
  39. window.onload = function()
  40. {
  41. var email = document.getElementById('email_select_all');
  42.  
  43. email.onclick = function(){
  44. return selectAll(email);
  45. };
  46. }

The Javascript will work on a HTML form like this

HTML:
  1. <form method="post">
  2.  
  3. <!-- Select all check box -->
  4. <input id="email_select_all" type="checkbox" />
  5.  
  6. <!-- list of check boxes -->
  7. <input type="checkbox" name="email_1" value="1" />
  8. <input type="checkbox" name="email_2" value="1" />
  9. <input type="checkbox" name="email_3" value="1"  />
  10. <input type="checkbox" name="email_4" value="1"  />
  11.  
  12. <input type="submit" value="Send Message" />
  13. </form>

As long at the select all checkbox has an id of "something_select_all" and the checkboxes have id's of "something_"followed by a number then this will work. No inline Javascript is required all the JS can be put in a separate file.

Note: If any Javascript Gurus are reading that have pointers about how I could improve this function then please put your suggestions in the comments.

# Pete Graham

Posted in Tech, javascript, Website Development, unobtrusive | 2 Comments »