Madproject

Always know where your towel is.

jQuery Checkbox select all

Ever wanted to allow a user to click the Select all checkbox and have all the checkboxes magically have checks in them?

You might want to do that if you have lots of options, especially if your checkboxes are being generated dynamically from information pulled from a database. The latter is what prompted me to add a select all button to one of my web apps. So like any developer who’s first, second or even third language isn’t Javascript, I fired up Google and searched for a solution.

The initial solution (not so good)

After copy pasting a bit of code here and there, I came up with a basic solution that uses document.getElementsByName

The Javascript looked like this:

<script type="text/javascript">
  function toggle(source,tgt) {
    checkboxes = document.getElementsByName(tgt);
    for(var i in checkboxes) checkboxes[i].checked = source.checked;
  }
</script>

The html:

<input type="checkbox" onClick="toggle(this, 'product[location_id][]')" />Select All<br/>

Now this worked fine until I tested it in IE. Dreaded IE! Turns out it doesn’t work because of an IE bug that doesn’t like document.getElementsByName

The best solution

So back to the drawing board or should I say Google. That’s when I found this gem: http://briancray.com/2009/08/06/check-all-jquery-javascript/

It uses jQuery which is a Javascript library. The brilliance is that it requires very little code upfront and it uses the fieldset html tag to wrap the checkboxes that you wish to check/uncheck with your select all checkbox. Therefore you can easily have many different checkbox groups with their own select all checkbox on the same page without any mixups.

Leave a Reply

Your email address will not be published. Required fields are marked *