Tuesday, September 22, 2009

Check/Uncheck all checkboxes in Jquery

This is simple, but want to show you how to get it working in simple and efficient way. Usually we have a parent check box and then some child checkboxes. Depends on the parent check box selection, all the child checkboxes should behave exactly same. So, below is the Jquery function which will do that magic for you.
function CheckUncheckAllCheckBoxes(objID, checkedValue) {
if (objID == null || objID == undefined )
return;

$(objID + " input[type=checkbox]").each(function() {
this.checked = checkedValue;
});
}
If you observe, I am using two parameters for the function named objID and checkedValue. objID is the parameter for knowing which checkbox group or list we need to check or uncheck? Like, on a page we may have many checkboxes and groups or lists. So, we need a way to find out which group or list we need to check or uncheck? For this reason I added a parameter for the function to check only the checkboxes under that ID or Class. Possible values for the objID are
  1. #parent Control ID of the element which has the check boxes declared. Example: #ageList
  2. .parent control class of the element under which all the check boxes defined. Example: .edit
And second parameter, it is for passing the parent selected check box value. If it is ON, then logic will loop through and set the each checkbox to checked otherwise unchecked.

Usage - How to call this method:
Code for check/Uncheck all in ASP.NET
$("#<%=cbAllStates.ClientID %>").click(function() {
   CheckUncheckAllCheckBoxes("#<%=cblState.ClientID %>", this.checked);
});
Note: cblAllStates is the parent ASP.NET check box which is controlling child. cblState is the asp.net checkboxlist and in our terms child check boxes.

Code for Check/Uncheck all in HTML:
$("#cbAllStates").click(function() {
   CheckUncheckAllCheckBoxes("#divChilds", this.checked);
});
Note: cbAllStates is the parent check box control and divChilds is the division <DIV< tag which has all the child check boxes present in it.

**UPDATED** 06/22/2010
This is the small update for the check/uncheck the all check box depends on the child check box selection. If any of the child check box is unchecked or the all child check boxes are selected then the all check box will toggle depends on it. Below is the work around.

Example:
Code for  Toggling the all check box depends on the child check boxes:
function ToggleSelectAllCheckBox(allCheckBox, checkedValue, obj) {
    if (allCheckBox == null || allCheckBox == undefined)
        return;
    if (!checkedValue) 
        $(allCheckBox).attr("checked", false);
    else {
        var areAllChecked = true;
        $(obj + " input[type=checkbox]").each(function() {
            if (!this.checked) {
                areAllChecked = false;                
            }
        });
        $(allCheckBox).attr("checked", areAllChecked);
    }
}
In the above function param1 is the all child check boxes, param2 is the current child check box selection and param3 is the all check box selector.

How to use:
ASP.NET Checkbox list:
$("#<%=cblAge.ClientID %> input[type=checkbox]").click(function() {
                ToggleSelectAllCheckBox("#<%=cbAllAges.ClientID %>", this.checked, "#<%=cblAge.ClientID %>");
 });
Note: cblAges is the check box list id and the cblAge is the all check box for the age group. So, the click event is for the all check boxes inside the check box list.

HTML Check boxes:
$(".ageGroup  input[type=checkbox]").click(function() {
                ToggleSelectAllCheckBox(".ageGroup", this.checked,  "#allAgeCheckbox");
 });
Note: ".ageGroup" is the div or some parent element which holds all the checkboxes in HTML. "#allAgeCheckbox" is the id of the all checkbox for that age group.

**End of Update**

Hope this will help you to understand how to write code in efficient way and which helps for us in multiple scenarios. Always welcome your valuable comments.

12 comments:

  1. Hi,

    Can you please help on how to check only certain which are under certain checkboxlist ,I think the above solution checks all the checkbox in the form.I tried different ways but didnt work

    Thanks

    ReplyDelete
  2. Hi Anushka,
    It's simple. That is why I wrote my function compatible to all the requirements. What you need to do is, just pass your check box list ID as the first argument of the function. For example,
    your check box list id is something like this "cblName" then your Jquery function call should look like this.
    CheckUncheckAllCheckBoxes("#cblName", true);
    Note: For server side controls you need to pass first parameter like CheckUncheckAllCheckBoxes("#<%=cblName.ClientID %>", true");
    Then it will look for the check boxes only which are in the scope of that ID.
    Hope this helps!!!
    Please let me know, if you have any issues or questions with it.

    -Praveen.

    ReplyDelete
  3. Hi,

    Thanks for the reply,havent tried the snippet earlier but was under impression was using similar functionality like this
    [code]
    $(document).ready(function() {
    $('#chkAll').click(
    function() {
    $("INPUT[type='checkbox']").attr('checked', $('#chkAll').is(':checked'));
    });
    });[/code]

    so in quick hurry got overlooked,Thanks for the clarification

    ReplyDelete
  4. Hi,

    This post is very helpful and the code snippet provided works great.Most of the snippets demonstrate how to check all the checkboxes on click but this post will be helpful in achieveing the check/uncheck of selected checkboxlist on click of parent of checkbox

    Thanks its saved hours of time

    Nice work

    ReplyDelete
  5. So Given this example..How do I add to it and handle users manually unchecking child checkboxes which would then require me to uncheck the checkall box..for instance..If I click checkall and then decide I want to uncheck one..the check all box should reflect that and uncheck itself

    ReplyDelete
  6. Hi Gumba,
    I have updated post with the toggle all check box which depends on the selection of the child check boxes. So, you can find it under the UPDATED section in this post. Thanks and let me know, if you need any more help.

    -Praveen.

    ReplyDelete
  7. Hi All,
    Nice post. I have multiple parents and many check-box under them, every parent/child has unique id. I want to check/un-check all child when i click on its respective parent.

    Thanx

    ReplyDelete
  8. Hi Omer,
    This is simple with this function.
    For example, in your case, there are 3 check box parent/child combination are there then simply do below.

    Combination 1:
    1. parent check box some id [No need of passing any parent id to function as we are not using id. We just need the checked value of parent for this function].
    2. All child check boxes are in some div or span or whatever which has the id as "child1Group".
    The same I am repeating for all other 2 like second child check box group is "child2Group" and third one is "child3Group".

    Now, the function will be called as
    CheckUncheckAllCheckBoxes("#child1Group", true);
    CheckUncheckAllCheckBoxes("#child2Group", true);
    CheckUncheckAllCheckBoxes("#child3Group", true);

    Remember, the second parameter true is just for example, this will be the actual value of parent check box of that specific group.

    Hope this helps. Let me know, if you have any questions still or problems in using it.

    thanks
    -Praveen.

    ReplyDelete
  9. Here is my solution that doesn't care what the id of the checkboxes is...It uses jQuery and will allow for multiple groups of parent/child checkboxes...

    http://tech.tiffanyandjeremy.com/Articles/Two-level-JQuery-check-and-uncheck-all-child-checkboxes-of-a-parent-checkbox

    ReplyDelete
  10. After searching a lot in Google and not finding any example that worked for me, this was really usefull. Thanks

    ReplyDelete
  11. what if i need to do it in one ASP control "checkboxlist"
    like : All
    one
    two
    three

    ReplyDelete
  12. Can you do this in A SharePoint DataView?

    ReplyDelete