1

I have the following code. It checks all the checkboxes on the page using the LABEL element which is usually on top of the checkboxes. Now how do I use the same LABEL element to uncheck all the boxes?

jQuery(document).ready(function($) {

 var $checkBoxes = $('input[type="checkbox"]');

 $('label').click(function() {
   $checkBoxes.attr('checked', true);
 });
});     
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Patoshi パトシ
  • 21,707
  • 5
  • 29
  • 47
  • what happens when some(not all) of the checkboxes are checked - would you check all or uncheck all? – wirey00 Jul 03 '13 at 20:48

5 Answers5

5

Use:

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
Anand Shah
  • 180
  • 5
3

For toggling, you need to store the state somewhere, like in data() :

jQuery(document).ready(function($) {
    var $checkBoxes = $('input[type="checkbox"]');

    $('label').on('click', function() {
        var check = !$(this).data('checked');
        $checkBoxes.prop('checked', check);
        $(this).data('checked', check);
    });
});    

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • In most systems I've used, the "check-all" element is also a checkbox, so you can just use its `:checked` state to save the value. – Barmar Jul 03 '13 at 20:52
  • @Barmar - in this case the OP has only stated that it's a label, and not if it contains a checkbox or not ? – adeneo Jul 03 '13 at 20:53
2

You can try something like:

var checked = 0;

$('label').click(function() {
   if(checked) {
       $checkBoxes.prop('checked', true);
       checked = 1;
   } else {
        $checkBoxes.prop('checked',false);
        checked = 0;
   }
 });
DarkAjax
  • 15,955
  • 11
  • 53
  • 65
0

First of all, use .prop() instead of .attr().

This code should work (not tested):

$checkBoxes.prop('checked', $checkBoxes.not(':checked').length ? true : false);

After a second reading, im not sure if that's what you want. Do you want a "checkall" button so when you click on it, if 1 or more checkboxes is unchecked, it check all else uncheck all or really a "toggle button"?

Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
0

All on or all off. Plus a closure to keep it all tightly scoped.

$('label').click((function () {

   var state = false;

   return function () {
      $checkBoxes.prop('checked', state = !state);
   };
}()));
John Strickler
  • 25,151
  • 4
  • 52
  • 68