433

I have the following:

$(document).ready(function()
{
    $("#select-all-teammembers").click(function() {
        $("input[name=recipients\\[\\]]").attr('checked', true);
    });                 
});

I'd like the id="select-all-teammembers" when clicked to toggle between checked and unchecked. Ideas? that aren't dozens of lines of code?

neophyte
  • 6,540
  • 2
  • 28
  • 43
AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

24 Answers24

785

You can write:

$(document).ready(function() {
    $("#select-all-teammembers").click(function() {
        var checkBoxes = $("input[name=recipients\\[\\]]");
        checkBoxes.prop("checked", !checkBoxes.prop("checked"));
    });                 
});

Before jQuery 1.6, when we only had attr() and not prop(), we used to write:

checkBoxes.attr("checked", !checkBoxes.attr("checked"));

But prop() has better semantics than attr() when applied to "boolean" HTML attributes, so it is usually preferred in this situation.

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • @AnApprentice, sorry, they're the same thing, I was just being silly ;) – Frédéric Hamidi Nov 14 '10 at 11:02
  • I used this to help me toggle single checkboxes on/off, too! Thanks for fantastic, brief, understandable code! – mbm29414 Jun 13 '12 at 12:05
  • 5
    This can get tangly as it bases the status off of the first one (so if the user checks the first one, then uses the toggle, they'll get out of sync). Slightly tweaked so it bases the status off of the toggle, not the first checkbox in the list: $("input[name=recipients\\[\\]]").prop("checked", $(this).prop("checked")); – CookiesForDevo Nov 12 '12 at 23:24
  • @Cookies, your solution is indeed less tangly, but it assumes the element matching `#select-all-teammembers` exposes a `checked` property (i.e. is itself a check box or a radio button). The question does not mention anything like that, and binding to `click` instead of `change` might arguably be a hint the element is not a check box (or radio button). Even if it was, its `name` attribute would also have to match `recipients\[\]` for this solution to work as intended. – Frédéric Hamidi Nov 12 '12 at 23:31
  • Ah, you're totally right — got too caught up in how I was using it. – CookiesForDevo Nov 13 '12 at 01:27
  • 6
    Using 'prop' makes this work for Zepto, too. Otherwise it will check the box, but will not uncheck it. – SimplGy Nov 25 '12 at 22:12
  • I had to use `checkBoxes.prop("checked", !checkBoxes.attr("checked"));` – Chris Edwards Jul 30 '13 at 17:57
  • 1
    "prop" instead of "attr" did the trick: with "attr" it toggles for a while and then stops, with "prop" instead it toggles as expected. +1 for the update. – Niki Romagnoli Nov 07 '13 at 22:55
  • 13
    `$('input[type=checkbox]').trigger('click');` mentioned by @2astalavista below is more succinct and also triggers the "change" event. – here Aug 27 '14 at 05:34
  • @here, the results won't be the same, though (2astalavista's answer effectively toggles the state of every check box, mine implements a select all / select none policy). Note in passing that triggering `click` events can have side effects, e.g. if handlers you do not control are listening to these clicks. – Frédéric Hamidi Aug 27 '14 at 05:58
  • @FrédéricHamidi you are totally right! Thanks for clarifying. – here Sep 04 '14 at 23:31
  • 1
    could you edit your answer to support @CookiesForDevo's answer – acquayefrank Apr 08 '16 at 14:34
  • @larry, you mean [that comment](http://stackoverflow.com/questions/4177159/toggle-checkboxes-on-off/4177175?noredirect=1#comment18225919_4177175)? Sorry, I won't, since that approach assumes too much. I explained why in [this comment](http://stackoverflow.com/questions/4177159/toggle-checkboxes-on-off/4177175?noredirect=1#comment18226017_4177175). – Frédéric Hamidi Apr 08 '16 at 14:46
  • The answer was a perfect fit, but, I have to add to details : 1 - It does not check/uncheck the input, I mean, not in the browser ( I am using firefox 62 on macos ), but, it triggers click and change events ! 2 - if I add a .trigger('click'), it will check/uncheck the input on browser, but, both events ( click and change ) will fire twice ! " checkBoxes.prop("checked", !checkBoxes.prop("checked")).trigger('click'); ". So anyhow to change the input on Browser and fire click event only once ? – Diego Favero Oct 11 '18 at 12:12
  • @here Another reason `trigger('click')` might not work: if you're in the click handler of a parent object like a `` cell that contains the checkbox. Then you get infinite recursion because the click event inherits all the way up! – Ethan T Sep 15 '20 at 02:07
  • For anyone looking for this, this is a more standard approach (uncheck if at least one is checked, check if none are checked): `checkBoxes.prop('checked', !$.makeArray(checkBoxes).some(function (x) { return x.checked }));` – Alberto Rechy Mar 04 '22 at 21:11
236
//this toggles the checkbox, and fires its event if it has    

$('input[type=checkbox]').trigger('click'); 
//or
$('input[type=checkbox]').click(); 
  • Works in chrome 29 but not in FF 17.0.7, can someone confirm that? – Gerrit-K Oct 01 '13 at 06:41
  • I had been going the route of changing the property for so long. For me this is a great and more flexible approach for checking and unchecking checkbox elements. – Isioma Nnodum Nov 25 '13 at 17:47
  • 2
    Unwanted event is triggered. – Jehong Ahn Nov 27 '19 at 05:37
  • 1
    For checkboxes, it is generally more advisable to fire the 'change' event, as they could be changed by clicking on a label. – Peter Mghendi Jan 15 '20 at 15:52
  • I like this too, for it's simplicity, but as @PeterLenjo said, you have to adjust things to accommodate for clicking on the label. I just prevented the label from toggling the checkbox altogether. – Nathan Mar 29 '22 at 17:10
72

I know this is old but the question was a bit ambiguous in that toggle may mean each checkbox should toggle its state, whatever that is. If you have 3 checked and 2 unchecked, then toggling would make the first 3 unchecked and the last 2 checked.

For that, none of the solutions here work as they make all the checkboxes have the same state, rather than toggle each checkbox's state. Doing $(':checkbox').prop('checked') on many checkboxes returns the logical AND between all .checked binary properties, i.e. if one of them is unchecked, the returned value is false.

You need to use .each() if you want to actually toggle each checkbox state rather than make them all equal, e.g.

   $(':checkbox').each(function () { this.checked = !this.checked; });

Note that you don't need $(this) inside the handler as the .checked property exists in all browsers.

Normadize
  • 1,156
  • 12
  • 22
16

Here is another way that you want.

$(document).ready(function(){   
    $('#checkp').toggle(
        function () { 
            $('.check').attr('Checked','Checked'); 
        },
        function () { 
            $('.check').removeAttr('Checked'); 
        }
    );
});
kst
  • 1,498
  • 3
  • 19
  • 34
  • 2
    @kst - This is a better method $('input[name=recipients\\[\\]]').toggle(this.checked); Forget the classes. – Davis Jan 14 '14 at 20:46
13

I think it's simpler to just trigger a click:

$("#select-all-teammembers").click(function() {
    $("input[name=recipients\\[\\]]").trigger('click');
});                 
matt burns
  • 24,742
  • 13
  • 105
  • 107
  • So much more effective as it also launches the 'onclick' function of the target chkbox.. – JonV Mar 23 '22 at 07:38
12

The best way I can think of.

$('#selectAll').change(function () {
    $('.reportCheckbox').prop('checked', this.checked);
});

or

$checkBoxes = $(".checkBoxes");
$("#checkAll").change(function (e) {
    $checkBoxes.prop("checked", this.checked);
});   

or

<input onchange="toggleAll(this)">
function toggleAll(sender) {
    $(".checkBoxes").prop("checked", sender.checked);
}
Dblock247
  • 6,167
  • 10
  • 44
  • 66
10

Use this plugin :

$.fn.toggleCheck  =function() {
       if(this.tagName === 'INPUT') {
           $(this).prop('checked', !($(this).is(':checked')));
       }

   }

Then

$('#myCheckBox').toggleCheck();
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
  • for me your sollution didn't work until I changed the if-statement like this: `if(this[0].tagName === 'INPUT')` – snecserc Jan 21 '22 at 09:52
9

Since jQuery 1.6 you can use .prop(function) to toggle the checked state of each found element:

$("input[name=recipients\\[\\]]").prop('checked', function(_, checked) {
    return !checked;
});
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • Excellent answer. Do you happen to know more about passing the underscore as the first param? Where could I learn more about that? – user1477388 Sep 09 '16 at 18:25
  • 1
    Edit: Apparently, it is essentially a means to pass null http://stackoverflow.com/questions/11406823/underscore-as-a-jquery-javascript-variable – user1477388 Sep 09 '16 at 18:27
  • This worked really great - Have been looking for a proptoggle for a while, and this worked clean. – Stender May 30 '23 at 08:14
2

Assuming that it's an image that has to toggle the checkbox, this works for me

<img src="something.gif" onclick="$('#checkboxid').prop('checked', !($('#checkboxid').is(':checked')));">
<input type="checkbox" id="checkboxid">
  • 4
    Since this is your first answer, realize that it is most often best to follow the pattern the poster used in the question - like putting the jQuery code in the document ready handler and not in-line in markup. IF you have a reason to NOT do that, add explaination as to why. – Mark Schultheiss May 31 '12 at 20:12
2

The most basic example would be:

// get DOM elements
var checkbox = document.querySelector('input'),
    button = document.querySelector('button');

// bind "cilck" event on the button
button.addEventListener('click', toggleCheckbox);

// when clicking the button, toggle the checkbox
function toggleCheckbox(){
  checkbox.checked = !checkbox.checked;
};
<input type="checkbox">
<button>Toggle checkbox</button>
vsync
  • 118,978
  • 58
  • 307
  • 400
2

if you want to toggle each box individually (or just one box works just as well):

I recommend using .each() , as it is easy to modify if you want different things to happen, and still relatively short and easy to read.

e.g. :

// toggle all checkboxes, not all at once but toggle each one for its own checked state:
$('input[type="checkbox"]').each(function(){ this.checked = ! this.checked });

// check al even boxes, uncheck all odd boxes:
$('input[type="checkbox"]').each(function(i,cb){ cb.checked = (i%2 == 0); });

// set all to checked = x and only trigger change if it actually changed:
x = true;
$('input[type="checkbox"]').each(function(){
    if(this.checked != x){ this.checked = x; $(this).change();}  
});

on a side note... not sure why everyone uses .attr() or .prop() to (un)check things.

as far as I know, element.checked has always worked the same in all browsers?

MoonLite
  • 4,981
  • 2
  • 21
  • 13
2

Check-all checkbox should be updated itself under certain conditions. Try to click on '#select-all-teammembers' then untick few items and click select-all again. You can see inconsistency. To prevent it use the following trick:

  var checkBoxes = $('input[name=recipients\\[\\]]');
  $('#select-all-teammembers').click(function() {
    checkBoxes.prop("checked", !checkBoxes.prop("checked"));
    $(this).prop("checked", checkBoxes.is(':checked'));
  }); 

BTW all checkboxes DOM-object should be cached as described above.

Anatoly
  • 15,298
  • 5
  • 53
  • 77
2

Here is a jQuery way to toggle checkboxes without having to select a checkbox with html5 & labels:

 <div class="checkbox-list margin-auto">
    <label class="">Compare to Last Year</label><br>
    <label class="normal" for="01">
       <input id="01" type="checkbox" name="VIEW" value="01"> Retail units
    </label>
    <label class="normal" for="02">
          <input id="02" type="checkbox" name="VIEW" value="02">  Retail Dollars
    </label>
    <label class="normal" for="03">
          <input id="03" type="checkbox" name="VIEW" value="03">  GP Dollars
    </label>
    <label class="normal" for="04">
          <input id="04" type="checkbox" name="VIEW" value="04">  GP Percent
    </label>
</div>

  $("input[name='VIEW']:checkbox").change(function() {
    if($(this).is(':checked')) {  
         $("input[name='VIEW']:checkbox").prop("checked", false);
     $("input[name='VIEW']:checkbox").parent('.normal').removeClass("checked");
         $(this).prop("checked", true);
         $(this).parent('.normal').addClass('checked');
    }
    else{
         $("input[name='VIEW']").prop("checked", false);
         $("input[name='VIEW']").parent('.normal').removeClass('checked');
    }    
});

http://www.bootply.com/A4h6kAPshx

yardpenalty.com
  • 1,244
  • 2
  • 17
  • 32
2

simply you can use this

$("#chkAll").on("click",function(){
    $("input[name=checkBoxName]").prop("checked",$(this).prop("checked"));
});
Fouad Mekkey
  • 138
  • 1
  • 7
1
jQuery("#checker").click(function(){
    jQuery("#mydiv :checkbox").each(function(){
        this.checked = true;
    });
});
jQuery("#dechecker").click(function(){
    jQuery("#mydiv :checkbox").each(function(){
        this.checked = false;
    });
});
jQuery("#checktoggler").click(function(){
    jQuery("#mydiv :checkbox").each(function(){
        this.checked = !this.checked;
    });
});

;)

Gigoland
  • 1,287
  • 13
  • 10
1

You can write like this also

$(function() {
    $("#checkbox-toggle").click(function() {
        $('input[type=checkbox][name=checkbox_id\\[\\]]').click();
    });
});

Just need to call click event of check box when user click on button with id '#checkbox-toggle'.

Milan Malani
  • 1,818
  • 1
  • 22
  • 34
1

A better approach and UX

$('.checkall').on('click', function() {
   var $checks  = $('checks');
   var $ckall = $(this);

    $.each($checks, function(){
        $(this).prop("checked", $ckall.prop('checked'));
    });
});

$('checks').on('click', function(e){
   $('.checkall').prop('checked', false);
});
Hugo Dias
  • 169
  • 3
  • 14
1
<table class="table table-datatable table-bordered table-condensed table-striped table-hover table-responsive">
<thead>
    <tr>
        <th class="col-xs-1"><a class="select_all btn btn-xs btn-info"> Select All </a></th>
        <th class="col-xs-2">#ID</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td><input type="checkbox" name="order333"/></td>
        <td>{{ order.id }}</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="order334"/></td>
        <td>{{ order.id }}</td>
    </tr>
</tbody>                  
</table>

Try:

$(".table-datatable .select_all").on('click', function () {
    $("input[name^='order']").prop('checked', function (i, val) {
        return !val;
    });
});
Karol May
  • 181
  • 2
  • 16
1

This one works very well for me.

   $("#checkall").click(function() {
       var fruits = $("input[name=fruits\\[\\]]");
        fruits.prop("checked", $(this).prop("checked"));
    });
sovantha
  • 259
  • 3
  • 16
  • 1
    you do realize you are giving the "checked" property the exact same value it already has, right? isn't it a bit embarrassing? you obviously meant to put a `!` sign before it.. – vsync Jul 17 '16 at 21:32
1

This code will toggle the check box upon clicking any toggle switch animator used in web templates. Replace ".onoffswitch-label" as available in your code. "checkboxID" is the checkbox toggled here.

$('.onoffswitch-label').click(function () {
if ($('#checkboxID').prop('checked')) 
 {
   $('#checkboxID').prop('checked', false);
 }
else 
 {
   $('#checkboxID').prop('checked', true);
 }
});
Pranesh Janarthanan
  • 1,134
  • 17
  • 26
1

You could also toggle-checkboxes-on-off by doing the following. Currently using bootstrap toggle checkboxes.

<link href='https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css' rel='stylesheet'>
<script src='https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js'></script>

<input type='checkbox' id='toggleScheduler' name='toggleScheduler' data-toggle='toggle'  data-on='Enabled'  data-off='Disabled'

$("#toggleScheduler").bootstrapToggle('on'); // enable toggle checkbox
$("#toggleScheduler").bootstrapToggle('off'); // disable toggle checkbox
Du-Lacoste
  • 11,530
  • 2
  • 71
  • 51
0

in my guess, the rightest man who suggested normal variant is GigolNet Gigolashvili, but i wanna suggest even more beautiful variant. Check it

$(document).on('click', '.fieldWrapper > label', function(event) {
    event.preventDefault()
    var n = $( event.target ).parent().find('input:checked').length
    var m = $( event.target ).parent().find('input').length
    x = n==m? false:true
    $( event.target ).parent().find('input').each(function (ind, el) {
        // $(el).attr('checked', 'checked');
        this.checked = x
    })
})
Arthur Sult
  • 676
  • 7
  • 10
0

Setting 'checked' or null instead of true or false respectively will do the work.

// checkbox selection
var $chk=$(':checkbox');
$chk.prop('checked',$chk.is(':checked') ? null:'checked');
I.P.Singh
  • 1
  • 1
-3

Well there is an easier way

First Give your checkboxes a class example 'id_chk'

Then inside the checkbox wich will control 'id_chk' checkboxes state put:

<input type='checkbox' onchange='js:jQuery(".id_chk").prop("checked", jQuery(this).prop("checked"))' />

Thats all, hope this helps

Angel
  • 453
  • 4
  • 4