AnApprentice
AnApprentice

Reputation: 111070

Toggle Checkboxes on/off

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?

Upvotes: 442

Views: 645633

Answers (24)

Du-Lacoste
Du-Lacoste

Reputation: 12797

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

Upvotes: 1

Dblock247
Dblock247

Reputation: 6755

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

Upvotes: 13

Fouad Mekkey
Fouad Mekkey

Reputation: 148

simply you can use this

$("#chkAll").on("click",function(){
    $("input[name=checkBoxName]").prop("checked",$(this).prop("checked"));
});

Upvotes: 2

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93531

Use this plugin :

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

   }

Then

$('#myCheckBox').toggleCheck();

Upvotes: 10

yardpenalty.com
yardpenalty.com

Reputation: 1244

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

Upvotes: 2

Pranesh Janarthanan
Pranesh Janarthanan

Reputation: 1194

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

Upvotes: 1

vsync
vsync

Reputation: 130670

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>

Upvotes: 2

sovantha
sovantha

Reputation: 259

This one works very well for me.

   $("#checkall").click(function() {
       var fruits = $("input[name=fruits\\[\\]]");
        fruits.prop("checked", $(this).prop("checked"));
    });

Upvotes: 1

Karol May
Karol May

Reputation: 291

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

Upvotes: 2

user669677
user669677

Reputation:

//this toggles the checkbox, and fires its event if it has    

$('input[type=checkbox]').trigger('click'); 
//or
$('input[type=checkbox]').click(); 

Upvotes: 239

Hugo Dias
Hugo Dias

Reputation: 169

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

Upvotes: 1

Milan Malani
Milan Malani

Reputation: 1922

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'.

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173662

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

Upvotes: 10

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 263147

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.

Upvotes: 801

I.P.Singh
I.P.Singh

Reputation: 1

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

Upvotes: 0

Arthur Sult
Arthur Sult

Reputation: 736

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

Upvotes: 0

Anatoly
Anatoly

Reputation: 15530

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.

Upvotes: 2

Gigoland
Gigoland

Reputation: 1463

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

;)

Upvotes: 1

Angel
Angel

Reputation: 473

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

Upvotes: -3

MoonLite
MoonLite

Reputation: 5301

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?

Upvotes: 2

matt burns
matt burns

Reputation: 25430

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

$("#select-all-teammembers").click(function() {
    $("input[name=recipients\\[\\]]").trigger('click');
});                 

Upvotes: 13

Normadize
Normadize

Reputation: 1222

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.

Upvotes: 74

user1428592
user1428592

Reputation: 29

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">

Upvotes: 2

kst
kst

Reputation: 1518

Here is another way that you want.

$(document).ready(function(){   
    $('#checkp').toggle(
        function () { 
            $('.check').attr('Checked','Checked'); 
        },
        function () { 
            $('.check').removeAttr('Checked'); 
        }
    );
});

Upvotes: 16

Related Questions