Tuesday, 30 December 2014

Gridview CheckBox checked and Unchecked With Javascript

1.) In Gridview   TemplateField

<asp:TemplateField HeaderStyle-Width="120px" HeaderStyle-HorizontalAlign="Center" >
                        <HeaderTemplate>
                            <asp:CheckBox runat="server" ID="chkAll" Text="Select All" />
                        </HeaderTemplate>
                        <ItemTemplate>
                            <asp:CheckBox ID="chkSelect" Runat="server" AutoPostBack="False"></asp:CheckBox>
                        </ItemTemplate>
                        <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
                        <HeaderStyle ForeColor="White" />
                    </asp:TemplateField>

2) Javascript for Check box

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#<%=gvInvoices.ClientID%> input[id*='chkSelect']:checkbox").click(function () {
            //Get number of checkboxes in list either checked or not checked
            var totalCheckboxes = $("#<%=gvInvoices.ClientID%> input[id*='chkSelect']:checkbox").size();
            //Get number of checked checkboxes in list
            var checkedCheckboxes = $("#<%=gvInvoices.ClientID%> input[id*='chkSelect']:checkbox:checked").size();
            //Check / Uncheck top checkbox if all the checked boxes in list are checked
            $("#<%=gvInvoices.ClientID%> input[id*='chkAll']:checkbox").attr('checked', totalCheckboxes == checkedCheckboxes);
        });

        $("#<%=gvInvoices.ClientID%> input[id*='chkAll']:checkbox").click(function () {
            //Check/uncheck all checkboxes in list according to main checkbox 
            $("#<%=gvInvoices.ClientID%> input[id*='chkSelect']:checkbox").attr('checked', $(this).is(':checked'));
        });
    });

</script>