Click here to Skip to main content
Click here to Skip to main content

Check/UnCheck All Checkboxes in CheckBoxList

By , 12 May 2013
 

Introduction

I needed a script to check/uncheck all the items in CheckBoxList in a gridview, but all the search lead to the use of two controls, one for the Select All and the other for the List itself.

Using the Code

I'll assume that the CheckBoxList already has items.

We will add attribute to each checkbox in the checkboxlist.

C#

foreach (ListItem item in chkList.Items)
            {
                item.Attributes.Add("onclick", "CheckStatus(this)");
                item.Selected = true;
            } 

JavaScript

function CheckStatus(chk) {
            $(document).ready(
            function () {
                var chkList = $($(chk).parents('table')).first();
                var firstCHK = $(chkList).find(':checkbox').first();
                if ($(firstCHK).attr('value') == 0) {
                    if ($(firstCHK).attr('value') == $(chk).attr('value')) {
                        $(chkList).find(':checkbox').each(function () {
                            this.checked = $(firstCHK).is(':checked');
                        });
                    }
                    else {
                        if ($(chk).is(':checked') == false) {
                            $(firstCHK).attr('checked', false);
                        }
                        else {
                            var flag = true;
                            $(chkList).find(':checkbox').each(function () {
                                if (this.checked == false && this.value != 0)
                                    flag = false;
                            });

                            $(firstCHK).prop('checked', flag);
                        }
                    }
                }
            });
        }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Dev.Tamer
Software Developer (Senior)
Egypt Egypt
Member
An Egyptian Senior Software Developer working in KSA-Riyadh

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130513.1 | Last Updated 12 May 2013
Article Copyright 2013 by Dev.Tamer
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid