jQuery: Invert a Selection of Checked Checkboxes CodeUnit 20 AUG 2010

If you have a group of checkboxes on a page, sometimes it is quite nice to give the user some quickfire controls that allows him to select all or select none at a click of a button. Similarly, it is pretty cool to give him the option of inverting his current selection, in other words checking all of those checkboxes currently unchecked, while unchecking all the currently ticked checkboxes.

To do this is fairly simple.

First, we built up a jQuery object containing all checked checkboxes. Then we repeat this for all unchecked checkboxes. Next, using the incredibly useful .each() function, we iterate over both collections and either set or unset the checked attribute accordingly.

In code, your invert function would look like this:

    var checked = $('.createrightcheckbox').filter(":checked");
    var unchecked = $('.createrightcheckbox').filter(":not(:checked)");


Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.

  • Daschmi

    Try: jQuery(“.selector”).attr(“checked”, !jQuery(this).is(“:checked”));