Tuesday, July 30, 2013

Check/uncheck CheckBox in a GridView using Javascript



 Gridview:
    <asp:GridView runat="server" ID="GV1">
        <Columns>

            <asp:TemplateField>
                <HeaderTemplate>                  
                    <asp:CheckBox ID="chkheader" runat="server" onclick="CheckAll(this)" />
                </HeaderTemplate>

                <ItemTemplate>
                    <asp:CheckBox ID="chkitem" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>

        </Columns>
    </asp:GridView>
   

Javascript
<script type="text/javascript">

        function SelectAll(status) {
            var gv = document.getElementById("<%=GV1.ClientID %>");
            var inputs = gv.getElementsByTagName("input");
            for (var i = 0; i < inputs.length; i++) {
                if (inputs[i].type == 'checkbox') {

                    inputs[i].checked = status;

                }
            }
        }

        function CheckAll(chkheader) {

            if (chkheader.checked) {

                SelectAll(true);
            }
            else {

                SelectAll(false);
            }

        }

    </script>

Note: OnClientClick is not available for checkbox. You can use onclick Event.