In jQuery how do you check and uncheck all checkboxes using an element? [duplicate]

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




$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

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



You can try something like:

var checked = 0;

$('label').click(function() {
   if(checked) {
       $checkBoxes.prop('checked', true);
       checked = 1;
   } else {
        checked = 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"?


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


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.