Tag Archives: invert

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:

$('#createrightstoggle').click(function(){
    var checked = $('.createrightcheckbox').filter(":checked");
    var unchecked = $('.createrightcheckbox').filter(":not(:checked)");
    checked.each(function(){$(this).prop('checked',false);});
    unchecked.each(function(){$(this).prop('checked',true);});
});

Nifty.

jQuery: Checking or Unchecking All Checkboxes CodeUnit 08 APR 2010

Providing functionality to check all, uncheck all or even to invert the checkboxes currently selected on a page is pretty simple to achieve with either plain old JavaScript or the newer, more flashy jQuery library. Important too if you think just how much more usable your site becomes with these handy shortcuts available to the user.

Now to select all checkboxes on a page and then check them, one simply has to make use of the handy INPUT[type=’checkbox’] jQuery selector call and then follow that up with an attr call in order to change the checked attribute status to true. Finally, you bundle this all up and apply it to the click event of some handy button or span and end up with this:

$('#selectall').click(function(){
	$("INPUT[type='checkbox']").attr('checked', true);
});

Similarly to untick all checkboxes on your page you would go with something like this:

$('#selectnone').click(function(){
	$("INPUT[type='checkbox']").attr('checked', false);
});

The final little piece of magic on display for today is the function to invert the current checkbox tick selection. Basically here we are going to scroll through each checkbox using jQuery’s handy each function and set the checked attribute accordingly based on its currently held value, which in code would look something like this:

$('#selectinvert').click(function(){
	$("INPUT[type='checkbox']").each(function(){
        	if (this.checked == false) {
			this.checked = true;
		} else {
			this.checked = false;
		}
	});
});

Deceptively simple, was it not? :P