Toggle Checkboxes on/off

JqueryCheckboxJquery SelectorsToggle

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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

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

Solution 3 - Jquery

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.

Solution 4 - Jquery

Here is another way that you want.

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

Solution 5 - Jquery

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

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

Solution 6 - Jquery

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

Solution 7 - Jquery

Use this plugin :

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

Then

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

Solution 8 - Jquery

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

Solution 9 - Jquery

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

Solution 10 - Jquery

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

Solution 11 - Jquery

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?

Solution 12 - Jquery

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.

Solution 13 - Jquery

simply you can use this

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

Solution 14 - Jquery

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>

Solution 15 - Jquery

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

;)

Solution 16 - Jquery

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

Solution 17 - Jquery

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

Solution 18 - Jquery

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

Solution 19 - Jquery

This one works very well for me.

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

Solution 20 - Jquery

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

Solution 21 - Jquery

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

Solution 22 - Jquery

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

Solution 23 - Jquery

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

Solution 24 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnApprenticeView Question on Stackoverflow
Solution 1 - JqueryFrédéric HamidiView Answer on Stackoverflow
Solution 2 - Jqueryuser669677View Answer on Stackoverflow
Solution 3 - JqueryNormadizeView Answer on Stackoverflow
Solution 4 - JquerykstView Answer on Stackoverflow
Solution 5 - Jquerymatt burnsView Answer on Stackoverflow
Solution 6 - JqueryDblock247View Answer on Stackoverflow
Solution 7 - JqueryAbdennour TOUMIView Answer on Stackoverflow
Solution 8 - JqueryJa͢ckView Answer on Stackoverflow
Solution 9 - Jqueryyardpenalty.comView Answer on Stackoverflow
Solution 10 - Jqueryuser1428592View Answer on Stackoverflow
Solution 11 - JqueryMoonLiteView Answer on Stackoverflow
Solution 12 - JqueryAnatolyView Answer on Stackoverflow
Solution 13 - JqueryFouad MekkeyView Answer on Stackoverflow
Solution 14 - JqueryvsyncView Answer on Stackoverflow
Solution 15 - JqueryGigolNftView Answer on Stackoverflow
Solution 16 - JqueryMilan MalaniView Answer on Stackoverflow
Solution 17 - JqueryHugo DiasView Answer on Stackoverflow
Solution 18 - JqueryKarol GontarskiView Answer on Stackoverflow
Solution 19 - JquerysovanthaView Answer on Stackoverflow
Solution 20 - JqueryPranesh JanarthananView Answer on Stackoverflow
Solution 21 - JqueryArthur SultView Answer on Stackoverflow
Solution 22 - JqueryI.P.SinghView Answer on Stackoverflow
Solution 23 - JqueryDu-LacosteView Answer on Stackoverflow
Solution 24 - JqueryAngelView Answer on Stackoverflow