How to check all checkboxes using jQuery?

JavascriptJqueryCheckbox

Javascript Problem Overview


I am not expert with jQuery but I have tried to create a little script for my application. I want to check all checkboxes but it isn't working correctly.

First I tried to use attr and after that I tried with prop but I'm doing something wrong.

I tried this first:

$("#checkAll").change(function(){
    
  if (! $('input:checkbox').is('checked')) {
      $('input:checkbox').attr('checked','checked');
  } else {
      $('input:checkbox').removeAttr('checked');
  }       
});

But this didn't work.

Next: This worked better than above code

$("#checkAll").change(function(){
    
  if (! $('input:checkbox').is('checked')) {
      $('input:checkbox').prop('checked',true);
  } else {
      $('input:checkbox').prop('checked', false);
  }       
});

Both examples don't work.

JSFiddle: http://jsfiddle.net/hhZfu/4/

Javascript Solutions


Solution 1 - Javascript

You need to use .prop() to set the checked property

$("#checkAll").click(function(){
    $('input:checkbox').not(this).prop('checked', this.checked);
});

Demo: Fiddle

Solution 2 - Javascript

Simply use the checked property of the checkAll and use use prop() instead of attr for checked property

Live Demo

 $('#checkAll').click(function () {    
     $('input:checkbox').prop('checked', this.checked);    
 });

Use prop() instead of attr() for properties like checked > As of jQuery 1.6, the .attr() method returns undefined for attributes > that have not been set. To retrieve and change DOM properties such as > the checked, selected, or disabled state of form elements, use the > .prop() method

You have same id for checkboxes and its should be unique. You better use some class with the dependent checkboxes so that it does not include the checkboxes you do not want. As $('input:checkbox') will select all checkboxes on the page. If your page is extended with new checkboxes then they will also get selected/un-selected. Which might not be the intended behaviour.

Live Demo

$('#checkAll').click(function () {    
    $(':checkbox.checkItem').prop('checked', this.checked);    
});

Solution 3 - Javascript

A complete solution is here.

$(document).ready(function() {
    $("#checkedAll").change(function() {
        if (this.checked) {
            $(".checkSingle").each(function() {
                this.checked=true;
            });
        } else {
            $(".checkSingle").each(function() {
                this.checked=false;
            });
        }
    });

    $(".checkSingle").click(function () {
        if ($(this).is(":checked")) {
            var isAllChecked = 0;

            $(".checkSingle").each(function() {
                if (!this.checked)
                    isAllChecked = 1;
            });

            if (isAllChecked == 0) {
                $("#checkedAll").prop("checked", true);
            }     
        }
        else {
            $("#checkedAll").prop("checked", false);
        }
    });
});

Html should be :

Single check box on checked three checkbox will be select and deselect.

<input type="checkbox" name="checkedAll" id="checkedAll" />

<input type="checkbox" name="checkAll" class="checkSingle" />
<input type="checkbox" name="checkAll" class="checkSingle" />
<input type="checkbox" name="checkAll" class="checkSingle" />

Hope this helps to someone as it did for me.

JS Fiddle https://jsfiddle.net/52uny55w/

Solution 4 - Javascript

I think when user select all checkbox manually then checkall should be checked automatically or user unchecked one of them from all selected checkbox then checkall should be unchecked automically. here is my code..

$('#checkall').change(function () {
    $('.cb-element').prop('checked',this.checked);
});

$('.cb-element').change(function () {
 if ($('.cb-element:checked').length == $('.cb-element').length){
  $('#checkall').prop('checked',true);
 }
 else {
  $('#checkall').prop('checked',false);
 }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<input type="checkbox" name="all" id="checkall" />Check All</br>
<input type="checkbox" class="cb-element" /> Checkbox  1</br>
<input type="checkbox" class="cb-element" /> Checkbox  2</br>
<input type="checkbox" class="cb-element" /> Checkbox  3

Solution 5 - Javascript

$(document).ready(function() {
  $("#parent").click(function() {
    $(".child").prop("checked", this.checked);
  });

  $('.child').click(function() {
    if ($('.child:checked').length == $('.child').length) {
      $('#parent').prop('checked', true);
    } else {
      $('#parent').prop('checked', false);
    }
  });
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<p><input type="checkbox" id="parent" /> Check/Uncheck All</p>
<ul>
  <li>
    <input type="checkbox" class="child" /> Checkbox 1</li>
  <li>
    <input type="checkbox" class="child" /> Checkbox 2</li>
  <li>
    <input type="checkbox" class="child" /> Checkbox 3</li>
</ul>

HTML:

<p><input type="checkbox" id="parent" /> Check/Uncheck All</p>
<ul>
  <li>
    <input type="checkbox" class="child" /> Checkbox 1</li>
  <li>
    <input type="checkbox" class="child" /> Checkbox 2</li>
  <li>
    <input type="checkbox" class="child" /> Checkbox 3</li>
</ul>

jQuery:

$(document).ready(function() {
  $("#parent").click(function() {
    $(".child").prop("checked", this.checked);
  });

  $('.child').click(function() {
    if ($('.child:checked').length == $('.child').length) {
      $('#parent').prop('checked', true);
    } else {
      $('#parent').prop('checked', false);
    }
  });
});

Solution 6 - Javascript

Why don't you try this (in the 2nd line where 'form#' you need to put the proper selector of your html form):

$('.checkAll').click(function(){
	$('form#myForm input:checkbox').each(function(){
		$(this).prop('checked',true);
   })    			
});

$('.uncheckAll').click(function(){
	$('form#myForm input:checkbox').each(function(){
		$(this).prop('checked',false);
   })    			
});

Your html should be like this:

<form id="myForm">
      <span class="checkAll">checkAll</span>
      <span class="uncheckAll">uncheckAll</span>
      <input type="checkbox" class="checkSingle"></input>
      ....
</form>

I hope that helps.

Solution 7 - Javascript

Simplest way I know:

$('input[type="checkbox"]').prop("checked", true);

Solution 8 - Javascript

$('#checkAll').on('change', function(){
    if($(this).attr('checked')){
        $('input[type=checkbox]').attr('checked',true);
    }
    else{
        $('input[type=checkbox]').removeAttr('checked');
    }
});

Solution 9 - Javascript

> One checkbox to rule them all

For people still looking for plugin to control checkboxes through one that's lightweight, has out-of-the-box support for UniformJS and iCheck and gets unchecked when at least one of controlled checkboxes is unchecked (and gets checked when all controlled checkboxes are checked of course) I've created a jQuery checkAll plugin.

Feel free to check the examples on documentation page.


For this question example all you need to do is:

$( "#checkAll" ).checkall({
    target: "input:checkbox"
});

Isn't that clear and simple?

Solution 10 - Javascript

    <p id="checkAll">Check All</p>
<hr />
<input type="checkbox" class="checkItem">Item 1
<input type="checkbox" class="checkItem">Item 2
<input type="checkbox" class="checkItem">Item3

And jquery

$(document).on('click','#checkAll',function () {
     $('.checkItem').not(this).prop('checked', this.checked);
 });

Solution 11 - Javascript

You can run .prop() on the results of a jQuery Selector directly even if it returns more than one result. So:

$("input[type='checkbox']").prop('checked', true)

Solution 12 - Javascript

my solution

$(function() {
    $(".checkAll").click(function(){
        checkwhat  = $(this).data("checkwhat");
        $('input:checkbox.'+checkwhat).not(this).prop('checked', this.checked);
    });
  });

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<lablel><input type="checkbox" name="chkSelectAll" class="checkAll" data-checkwhat="chkSelect">check all group 1</lablel>
<br>
<input class="chkSelect" type="checkbox" name="chkSelect[]" value="1">  value 1.1<br>
<input class="chkSelect" type="checkbox" name="chkSelect[]" value="2"> value 1.2<br>
<input class="chkSelect" type="checkbox" name="chkSelect[]" value="3">  value 1.2<br>
<br>
<br>
<lablel><input type="checkbox" name="chkSelectAll" class="checkAll" data-checkwhat="chkSelect2">check all group 1</lablel>
<br>
<input class="chkSelect2" type="checkbox" name="chkSelect[]" value="1"> value 2.1<br>
<input class="chkSelect2" type="checkbox" name="chkSelect[]" value="4">value 2.1<br>

Solution 13 - Javascript

Usually you also want the master checkbox to be unchecked if at least 1 slave checkbox is unchecked and to be ckecked if all slave checkboxes are checked:

/**
 * Checks and unchecks checkbox-group with a master checkbox and slave checkboxes
 * @param masterId is the id of master checkbox
 * @param slaveName is the name of slave checkboxes
 */
function checkAll(masterId, slaveName) {
	$master = $('#' + masterId);
	$slave = $('input:checkbox[name=' + slaveName + ']');
	
	$master.click(function(){
		$slave.prop('checked', $(this).prop('checked'));
		$slave.trigger('change');
	});
	
	$slave.change(function() {
		if ($master.is(':checked') && $slave.not(':checked').length > 0) {
			$master.prop('checked', false);
		} else if ($master.not(':checked') && $slave.not(':checked').length == 0) {
		$master.prop('checked', 'checked');
	}
	});
}

And if you want to enable any control (e.g. Remove All button or a Add Something button), when at least one checkbox is checked and disable when no checkbox is checked:

/**
 * Checks and unchecks checkbox-group with a master checkbox and slave checkboxes,
 * enables or disables a control when a checkbox is checked
 * @param masterId is the id of master checkbox
 * @param slaveName is the name of slave checkboxes
 */
function checkAllAndSwitchControl(masterId, slaveName, controlId) {
	$master = $('#' + masterId);
	$slave = $('input:checkbox[name=' + slaveName + ']');
	
	$master.click(function(){
		$slave.prop('checked', $(this).prop('checked'));
		$slave.trigger('change');
	});
	
	$slave.change(function() {
		switchControl(controlId, $slave.filter(':checked').length > 0);
		if ($master.is(':checked') && $slave.not(':checked').length > 0) {
			$master.prop('checked', false);
		} else if ($master.not(':checked') && $slave.not(':checked').length == 0) {
		$master.prop('checked', 'checked');
	}
	});
}

/**
 * Enables or disables a control
 * @param controlId is the control-id
 * @param enable is true, if control must be enabled, or false if not
 */
function switchControl(controlId, enable) {
	var $control = $('#' + controlId);
	if (enable) {
		$control.removeProp('disabled');
	} else {
    	$control.prop('disabled', 'disabled');
    }
}

Solution 14 - Javascript

HTML

<HTML>
<HEAD>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <TITLE>Multiple Checkbox Select/Deselect - DEMO</TITLE>
</HEAD>
<BODY>
    <H2>Multiple Checkbox Select/Deselect - DEMO</H2>
<table border="1">
<tr>
    <th><input type="checkbox" id="selectall"/></th>
    <th>Cell phone</th>
    <th>Rating</th>
</tr>
<tr>
    <td align="center"><input type="checkbox" class="case" name="case" value="1"/></td>
    <td>BlackBerry Bold 9650</td>
    <td>2/5</td>
</tr>
<tr>
    <td align="center"><input type="checkbox" class="case" name="case" value="2"/></td>
    <td>Samsung Galaxy</td>
    <td>3.5/5</td>
</tr>
<tr>
    <td align="center"><input type="checkbox" class="case" name="case" value="3"/></td>
    <td>Droid X</td>
    <td>4.5/5</td>
</tr>
<tr>
    <td align="center"><input type="checkbox" class="case" name="case" value="4"/></td>
    <td>HTC Desire</td>
    <td>3/5</td>
</tr>
<tr>
    <td align="center"><input type="checkbox" class="case" name="case" value="5"/></td>
    <td>Apple iPhone 4</td>
    <td>5/5</td>
</tr>
</table>
 
</BODY>
</HTML>

jQuery Code

<SCRIPT language="javascript">
$(function(){
 
    // add multiple select / deselect functionality
    $("#selectall").click(function () {
          $('.case').attr('checked', this.checked);
    });
 
    // if all checkbox are selected, check the selectall checkbox
    // and viceversa
    $(".case").click(function(){
 
        if($(".case").length == $(".case:checked").length) {
            $("#selectall").attr("checked", "checked");
        } else {
            $("#selectall").removeAttr("checked");
        }
 
    });
});
</SCRIPT>

View Demo

Click here to View Demo

Solution 15 - Javascript

use .prop() to get the value of a property

$("#checkAll").change(function () {
    $("input:checkbox").prop('checked', $(this).prop("checked"));
});

Solution 16 - Javascript

i know there are lot of answer posted here but i would like to post this for optimization of code and we can use it globally.

i tried my best

/*----------------------------------------
 *  Check and uncheck checkbox which will global
 *  Params : chk_all_id=id of main checkbox which use for check all dependant, chk_child_pattern=start pattern of the remain checkboxes 
 *  Developer Guidline : For to implement this function Developer need to just add this line inside checkbox {{ class="check_all" dependant-prefix-id="PATTERN_WHATEVER_U_WANT" }}
 ----------------------------------------*/
function checkUncheckAll(chk_all_cls,chiled_patter_key){
	if($("."+chk_all_cls).prop('checked') == true){
		$('input:checkbox[id^="'+chiled_patter_key+'"]').prop('checked', 'checked');
	}else{
		$('input:checkbox[id^="'+chiled_patter_key+'"]').removeProp('checked', 'checked');
	}        
}

if($(".check_all").get(0)){
	var chiled_patter_key = $(".check_all").attr('dependant-prefix-id');
	
	$(".check_all").on('change',function(){        
		checkUncheckAll('check_all',chiled_patter_key);
	});
	
	/*------------------------------------------------------
	 * this will remain checkbox checked if already checked before ajax call! :)
	 ------------------------------------------------------*/
	$(document).ajaxComplete(function() {
		checkUncheckAll('check_all',chiled_patter_key);
	});
}

I hope this will help!

Solution 17 - Javascript

function checkAll(class_name) {
    $("." + class_name).each(function () { 
        if (this.checked == true) 
            this.checked = false; 
        else 
            this.checked = true; 
    }); 
}

Solution 18 - Javascript

checkall is the id of allcheck box and cb-child is the name of each checkboxes that will be checked and unchecked depend on checkall click event

$("#checkall").click(function () {
                        if(this.checked){
                            $("input[name='cb-child']").each(function (i, el) {
                                el.setAttribute("checked", "checked");
                                el.checked = true;
                                el.parentElement.className = "checked";

                            });
                        }else{
                            $("input[name='cb-child']").each(function (i, el) {
                                el.removeAttribute("checked");
                                el.parentElement.className = "";
                            });
                        }
                    });

Solution 19 - Javascript

***JAVA SCRIPT TO SELECT ALL CHECK BOX ***

Best Solution.. Try it

<script type="text/javascript">
        function SelectAll(Id) {
            //get reference of GridView control
            var Grid = document.getElementById("<%= GridView1.ClientID %>");
            //variable to contain the cell of the Grid
            var cell;

            if (Grid.rows.length > 0) {
                //loop starts from 1. rows[0] points to the header.
                for (i = 1; i < grid.rows.length; i++) {
                    //get the reference of first column
                    cell = grid.rows[i].cells[0];

                    //loop according to the number of childNodes in the cell
                    for (j = 0; j < cell.childNodes.length; j++) {
                        //if childNode type is CheckBox                 
                        if (cell.childNodes[j].type == "checkbox") {
                            //Assign the Status of the Select All checkbox to the cell checkbox within the Grid
                            cell.childNodes[j].checked = document.getElementById(Id).checked;
                        }
                    }
                }
            }
        }
    </script>

Solution 20 - Javascript

You Can use below Simple Code:

function checkDelBoxes(pForm, boxName, parent)
{
	for (i = 0; i < pForm.elements.length; i++)
		if (pForm.elements[i].name == boxName)
			pForm.elements[i].checked = parent;
}

Example for Using:

<a href="javascript:;" onclick="javascript:checkDelBoxes($(this).closest('form').get(0), 'CheckBox[]', true);return false;"> Select All
</a>
<a href="javascript:;" onclick="javascript:checkDelBoxes($(this).closest('form').get(0), 'CheckBox[]', false);return false;"> Unselect All
</a>

Solution 21 - Javascript

if(isAllChecked == 0)
{ 
    $("#select_all").prop("checked", true); 
}   

please change the above line to

if(isAllChecked == 0)
{ 
    $("#checkedAll").prop("checked", true); 
}   

in SSR's answer and its working perfect Thank you

Solution 22 - Javascript

if($('#chk_all').is(":checked"))
 {
    $('#'+id).attr('checked', true);
 }
else
 {
    $('#'+id).attr('checked', false);
 }  

   

Solution 23 - Javascript

function chek_al_indi(id)
{
	var k = id;
	var cnt_descriptiv_indictr = eval($('#cnt_descriptiv_indictr').val());
	var std_cnt = 10;

	if ($('#'+ k).is(":checked"))
	{
		for (var i = 1; i <= std_cnt; i++)	
		{
		    $("#chk"+ k).attr('checked',true);	
			k = k + cnt_descriptiv_indictr;
		}
	}

	if ($('#'+ k).is(":not(:checked)"))
	{
		for (var i = 1; i <= std_cnt; i++)	
		{
			$("#chk"+ k).attr('checked',false);  	
			k = k + cnt_descriptiv_indictr;
		}		
	}
}

Solution 24 - Javascript

 $('#checkall').on("click",function(){
      $('.chk').trigger("click");
   });

Solution 25 - Javascript

html :

    <div class="col-md-3 general-sidebar" id="CategoryGrid">
                                                    <h5>Category &amp; Sub Category <span style="color: red;">* </span></h5>
                                                    <div class="checkbox">
                                                        <label>
                                                            <input onclick="checkUncheckAll(this)" type="checkbox">
                                                            All
                                                        </label>
                                                    </div>
                                                <div class="checkbox"><label><input class="cat" type="checkbox" value="Quality">Quality</label></div>
<div class="checkbox"><label><input class="subcat" type="checkbox" value="Planning process and execution">Planning process and execution</label></div>

javascript:

function checkUncheckAll(ele) {
    if (ele.checked) {
        $('.cat').prop('checked', ele.checked);
        $('.subcat').prop('checked', ele.checked);
    }
    else {
        $('.cat').prop('checked', ele.checked);
        $('.subcat').prop('checked', ele.checked);
    }
}

Solution 26 - Javascript

            <pre>
            <SCRIPT language="javascript">
            $(function(){
                // add multiple select / deselect functionality
                $("#selectall").click(function () {
                      $('.case').attr('checked', this.checked);
                });
            
                // if all checkbox are selected, check the selectall checkbox
                // and viceversa
                $(".case").click(function(){
            
                    if($(".case").length == $(".case:checked").length) {
                        $("#selectall").attr("checked", "checked");
                    } else {
                        $("#selectall").removeAttr("checked");
                    }
            
                });
            });
            </SCRIPT>
            <HTML>
            <HEAD>
            <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
            <TITLE>Multiple Checkbox Select/Deselect - DEMO</TITLE>
            </HEAD>
            <BODY>
            <H2>Multiple Checkbox Select/Deselect - DEMO</H2>
            <table border="1">
              <tr>
                <th><input type="checkbox" id="selectall"/></th>
                <th>Cell phone</th>
                <th>Rating</th>
              </tr>
              <tr>
                <td align="center"><input type="checkbox" class="case" name="case" value="1"/></td>
                <td>BlackBerry Bold 9650</td>
                <td>2/5</td>
              </tr>
              <tr>
                <td align="center"><input type="checkbox" class="case" name="case" value="2"/></td>
                <td>Samsung Galaxy</td>
                <td>3.5/5</td>
              </tr>
              <tr>
                <td align="center"><input type="checkbox" class="case" name="case" value="3"/></td>
                <td>Droid X</td>
                <td>4.5/5</td>
              </tr>
              <tr>
                <td align="center"><input type="checkbox" class="case" name="case" value="4"/></td>
                <td>HTC Desire</td>
                <td>3/5</td>
              </tr>
              <tr>
                <td align="center"><input type="checkbox" class="case" name="case" value="5"/></td>
                <td>Apple iPhone 4</td>
                <td>5/5</td>
              </tr>
            </table>
            </BODY>
            </HTML>
            </pre>

Solution 27 - Javascript

Trigger Click

$("#checkAll").click(function(){
    $('input:checkbox').click();
});

OR

$("#checkAll").click(function(){
    $('input:checkbox').trigger('click');
});

OR

$("#checkAll").click(function(){
    $('input:checkbox').prop('checked', this.checked);
});

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
QuestionIvanView Question on Stackoverflow
Solution 1 - JavascriptArun P JohnyView Answer on Stackoverflow
Solution 2 - JavascriptAdilView Answer on Stackoverflow
Solution 3 - JavascriptSSRView Answer on Stackoverflow
Solution 4 - JavascriptAnkitView Answer on Stackoverflow
Solution 5 - JavascriptzarpioView Answer on Stackoverflow
Solution 6 - JavascriptioaniatrView Answer on Stackoverflow
Solution 7 - JavascriptDavidson LimaView Answer on Stackoverflow
Solution 8 - JavascriptSunnyView Answer on Stackoverflow
Solution 9 - JavascriptnassView Answer on Stackoverflow
Solution 10 - JavascriptdemenvilView Answer on Stackoverflow
Solution 11 - JavascriptechoView Answer on Stackoverflow
Solution 12 - JavascriptHoàng VÅ© TgttView Answer on Stackoverflow
Solution 13 - JavascriptLowLevelView Answer on Stackoverflow
Solution 14 - JavascriptPK-1825View Answer on Stackoverflow
Solution 15 - JavascriptphoenixView Answer on Stackoverflow
Solution 16 - JavascriptAshok ChandrapalView Answer on Stackoverflow
Solution 17 - JavascriptGanga ReddyView Answer on Stackoverflow
Solution 18 - JavascriptTanvirChowdhuryView Answer on Stackoverflow
Solution 19 - JavascriptCodeView Answer on Stackoverflow
Solution 20 - JavascriptNavid VakiliView Answer on Stackoverflow
Solution 21 - JavascriptPremjithView Answer on Stackoverflow
Solution 22 - JavascriptDsu MenariaView Answer on Stackoverflow
Solution 23 - JavascriptDsu MenariaView Answer on Stackoverflow
Solution 24 - JavascriptBharat ParmarView Answer on Stackoverflow
Solution 25 - JavascriptJaydeep ShilView Answer on Stackoverflow
Solution 26 - JavascriptPramod JainView Answer on Stackoverflow
Solution 27 - JavascriptjmnView Answer on Stackoverflow