Saturday, May 5, 2012

Check/UnCheck all checkboxes in a div through JQuery

This is very common functionality in any application where we have to give user the option to select or deselect all checkboxes.
So here is the code to do it in a very simple and easy way, I have put all the checkboxes in dvMain div and loop through each checkbox with JQuery each loop and then check or uncheck that paricular checkbox accordingly.

CODE

<head runat="server">
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
 
   <script type="text/javascript" language="javascript">

        function CheckAll() {
            $('#dvMain :checkbox').each(function () {     //loop all checkbox in dvMain div
                $(this).attr('checked', true);                    //This will check the current checkbox
            });
        }

        function UnCheckAll() {
            $('#dvMain :checkbox').each(function () {     //loop all checkbox in dvMain div
                $(this).attr('checked', false);                   //This will uncheck the current checkbox
            });
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="dvMain">

        <a href="javascript:" onclick="CheckAll()">Check All</a>
        <a href="javascript:" onclick="UnCheckAll()">Un Check All</a>
        <br />
        <asp:CheckBox ID="CheckBox0" runat="server" Text="BlackBerry" /><br />
        <asp:CheckBox ID="CheckBox1" runat="server" Text="iPhone" /><br />
        <asp:CheckBox ID="CheckBox2" runat="server" Text="Android" /><br />
        <asp:CheckBox ID="CheckBox3" runat="server" Text="Windows Phone" /><br />
        <asp:CheckBox ID="CheckBox4" runat="server" Text="Mego" /><br /><br />

        </div>
    </form>
</body>

I have used jquery-1.4.1 but other versions can also be used.

2 comments: