While working on a recent project at my job, I ran into a situation where I needed a form with a vertical column of checkboxes. At the top of them, I wanted to place a checkbox that when checked, would toggle the checkboxes below it.

Checkboxes

Checkboxes

I happen to be using a Rails app that has Prototype.js. The javascript to hook into the top-most checkbox and make it do our bidding looks something like this:

Event.observe(window, 'load', function() {
  var select_all_box = $('select_all_box');
  if (select_all_box) {
    var checkboxes = select_all_box.up('form').getInputs('checkbox');
    checkboxes.shift(); // throw out select all box
 
    select_all.observe('click', function() {
      checkboxes.each(function(e) {
        e.checked = select_all.checked;
      });
    });
  }
});

As you can see from the outer-most observe call, I’ve written this to be unobtrusive. With the page finished loading, we look for the checkbox we want to enhance. The HTML for the above screenshot is just a simple <table> contained within a <form>.  From there, grab all of the checkboxes in the form and then throw away the first one. Then create an event listener for the checkbox that iterates over the rest of the checkboxes matching them to the current state of the check-all box. Every time you check or uncheck the box at the top, all of the checkboxes below will follow.