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);
 });
});     
4

5 回答 5

5

Use:

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
于 2013-07-03T20:48:13.177 回答
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

于 2013-07-03T20:49:10.760 回答
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;
   }
 });
于 2013-07-03T20:49:03.743 回答
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"?

于 2013-07-03T20:50:34.770 回答
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);
   };
}()));
于 2013-07-03T20:52:29.097 回答