jQuery checkbox goodness

I was working on a select all feature today and just wanted to share this with the world. (a.k.a. keep it for later)


$(document).ready( function() {
$('a#select_all').click( function() {
$('input:checkbox').each( function() {
this.checked = !this.checked;
});
return false;
});
});

The first item to note is that jQuery created pseudo classes for input.

$('input:checkbox');
...
$('input:textbox');
... etc.

The second item to note, which I thought was ingenious, was setting the value of the checkbox to the inverse of it's current value.

this.checked = !this.checked;

Works great and it's short and sweet. Who loves jQuery?

Comments

yeah but

This words to "select all" checkboxes only if no checkboxes are currently selected. I believe what you've written *toggles* all checkboxes. Probably not the desired functionality.

Toggle all based on first checkbox state.


$.fn.check = function(mode,all) {
var mode = mode || 'on'; // if mode is undefined, use 'on' as default
var toggle_state = 'foo';
return this.each(function() {
if(toggle_state == 'foo' && all==true){
// toggle all of them the same, based on first one
toggle_state = !this.checked;
} else if(all!=true) {
// toggle each one individually
toggle_state = !this.checked;
alert(toggle_state);
}
switch(mode) {
case 'on':
this.checked = true;
break;
case 'off':
this.checked = false;
break;
case 'toggle':
this.checked = toggle_state;
break;
}
});
};

USE

< a href="#" onclick="$('.checkboxclass').check('toggle',true);return false;">ALL</a >
OR
< a href="#" onclick="$('.somecontainer :checkbox').check('toggle',true);return false;">ALL</a >

Posted this on PhpCrap.com as Jquery check boxes

Thanks!
C.Peterson

Accessing checkboxes

You can also access checkboxes like such:

$("#someDiv :checkbox");

which retrieves every checkbox in 'somediv'

--Dreas.
itoar.info - where geeks learn...

Thank you very much!

Thank you very much!

Great :)

Great :)

Very helpful!

Thanks for posting this... made my day easier

cute.

cute.

very cute indeed

very cute indeed