166

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/

3

27 Answers 27

381

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

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

Demo: Fiddle

7
  • 1
    Wow thanks for fast answer. This work good but in my app i have one fake check. when i refresh page ctrl+r and click on checkbox checkAll he dont check me all. After that i must check again to be successfull. So i need 2x click on checkAll whay that dont work on single click(one)? I copy paste that code and make function checkAll() and in checkbox i set onclick="return checkAll()"
    – Ivan
    Aug 30, 2013 at 16:41
  • 3
    If you're going to use jQuery, then use jQuery. It's not a good idea to mix up jQuery with inline Javascript. For example, this is bad: <elementtag id="someID" onclick="javascript code here" --- Instead, use jQuery: $('#someID').click(function() { checkAll() });
    – cssyphus
    Aug 30, 2013 at 16:57
  • 5
    What is the difference between your post this answer , why used not(this).prop ?
    – Shaiju T
    Nov 16, 2016 at 8:00
  • 1
    @ArunPJohny, id should be unique in a single page, how we can use same function using class example jsfiddle.net/52uny55w
    – jvk
    Jan 24, 2018 at 17:28
  • @ArunPJohny, thanks for you time. I want to learn many things from you on jquery, can you suggest me on jquery
    – jvk
    Jan 26, 2018 at 16:55
67

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

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/

5
  • 3
    I like this solution since if you uncheck one of the boxes, the "Check All" box also becomes unchecked. Likewise, if you manually check all the corresponding boxes, the "Check All" box gets checked, too. That is great UI feedback there!
    – HPWD
    Dec 22, 2017 at 19:16
  • 2
    You can make $("#checkedAll").change function shorter by changing it to: var val = this.checked; $(".checkSingle").each( function() { this.checked=val; });
    – Gellie Ann
    Feb 21, 2020 at 4:07
  • 1
    Also, I think it's better to rename the isAllChecked variable to isThereUnchecked or unChecked so it will be more descriptive on what the variable was used for.
    – Gellie Ann
    Feb 21, 2020 at 4:25
  • 1
    I took this solution, this is what i'm looking for thanks
    – Ajay Kumar
    Mar 11, 2020 at 8:50
  • This is what I'm looking for a long time... Thnx!
    – Wilf
    Jul 5, 2021 at 9:58
15

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

1
  • Thank you! I prefer this because after all checkbox checked, when we uncheck one of them, check all checkbox will be unchecked. Dec 10, 2019 at 1:01
13

$(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);
    }
  });
});
8

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.

5

Simplest way I know:

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

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

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

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?

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

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)

1

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>

0

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

0

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

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

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!

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

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 = "";
                            });
                        }
                    });
0

*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>
-1

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

-1
if($('#chk_all').is(":checked"))
 {
    $('#'+id).attr('checked', true);
 }
else
 {
    $('#'+id).attr('checked', false);
 }  
2
  • Would be handy if you explained the answer.
    – enkor
    Mar 2, 2015 at 15:21
  • if you check the check box then all check box are checked as ID and then you uncheck the check box then all check box unchecked Mar 12, 2015 at 11:04
-1
 $('#checkall').on("click",function(){
      $('.chk').trigger("click");
   });
-1

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);
    }
}
-1
            <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>
1
  • script error in the code. script needs to be loaded first. Jun 7, 2017 at 18:48
-1
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;
        }       
    }
}
1
-2

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.