Selecting all checkboxes in a group with Mootools, one-liner

Fairly common..?

Fairly common..?

How many times have you had to do one of these things? A group of items, each with a checkbox. You want a button/checkbox to select all the checkboxes within that group.

I ran across this again today, and making the javascript to do the work I was once again reminded why I love Mootools so much:

With just three lines of code (1 line to do the actual checking/unchecking), I had this up and running. It couldn’t have taken longer than 30 seconds to write. I love quick snippets ;-)

Obviously, this wouldn’t be hard to do in jQuery or any other JS framework, but I love how elegant and intuitive Mootools does it. I shudder when I think of how many times I’ve done things similar to this in plain old Javascript.

Anyway, there’s a demo page available, and here’s the code I ended up with, for anyone interested:

$$('li.head input[type=checkbox]').addEvent('click', function() {
this.getParent('ul').getElements('input[type=checkbox]').setProperty('checked', this.checked);
});

Tags: ,


One Response to “Selecting all checkboxes in a group with Mootools, one-liner”

  1. Chris Bolson says:

    I realize that this is a few months old, but I just came accross this post as I was searching for exactly this.
    It has to be said that this is an awesome one-liner!
    Thanks for sharing :)
    Chris

Leave a Reply