Check/Uncheck checkboxes in GridView using JavaScript

 Rate It (33)

The question regarding how to check/uncheck CheckBoxes within a GridView control using JavaScript has been asked many times. Here is a quick reference you can follow.

First we have the .aspx markup.

<script type="text/javascript">

    function SelectAll(id) {

        var frm = document.forms[0];

        for (i=0;i<frm.elements.length;i++) {

            if (frm.elements[i].type == "checkbox") {

                frm.elements[i].checked = document.getElementById(id).checked;

            }

        }

    } 

</script>

<!-- assuming that SqlDataSource1 is the datasource for my GridView -->

<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" Width="400px">

    <Columns>

        <asp:TemplateField>

            <AlternatingItemTemplate>

                <asp:CheckBox ID="CheckBox1" runat="server" />

            </AlternatingItemTemplate>

            <ItemTemplate>

                <asp:CheckBox ID="CheckBox1" runat="server" />

            </ItemTemplate>

            <HeaderTemplate>

                <asp:CheckBox ID="cbSelectAll" runat="server" Text="Select All" />

            </HeaderTemplate>

            <HeaderStyle HorizontalAlign="Left" />

            <ItemStyle HorizontalAlign="Left" />

        </asp:TemplateField>

    </Columns>

</asp:GridView>

Next we have the code-behind in both VB and C#

VB

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

    If (e.Row.RowType = DataControlRowType.Header) Then

        'adding an attribute for onclick event on the check box in the header

        'and passing the ClientID of the Select All checkbox

        DirectCast(e.Row.FindControl("cbSelectAll"), CheckBox).Attributes.Add("onclick", "javascript:SelectAll('" & _

            DirectCast(e.Row.FindControl("cbSelectAll"), CheckBox).ClientID & "')")

    End If

End Sub

C#

protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) {

    if (e.Row.RowType == DataControlRowType.Header) {

        //adding an attribute for onclick event on the check box in the header

        //and passing the ClientID of the Select All checkbox

        ((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "')");

    }

}

The example above is fantastic, but there are a couple things that could be improved.

  1. The JavaScript Pseudo Protocol (Javascript:your method here) should be avoided, it's a fragment from the old Netscape days. Today there are better alternatives
  2. In this case we probably don't need the server-side portion altogether.

An excerpt about the JavaScript Pseudo Protocol:

"The javascript: pseudo-protocol should not be used in event handlers like onclick. It should only be used in attributes that contain a URL, for example in the href attribute of <a> elements and the action attribute of <form> elements. You can also use it to make bookmarlets." - Common JavaScript Mistakes

Another solution the .aspx markup: 

<script type="text/javascript">

    // Let's use a lowercase function name to keep with JavaScript conventions

    function selectAll(involker) {

        // Since ASP.NET checkboxes are really HTML input elements

        //  let's get all the inputs

        var inputElements = document.getElementsByTagName('input');

 

        for (var i = 0 ; i < inputElements.length ; i++) {

            var myElement = inputElements[i];

 

            // Filter through the input types looking for checkboxes

            if (myElement.type === "checkbox") {

 

               // Use the involker (our calling element) as the reference 

               //  for our checkbox status

                myElement.checked = involker.checked;

            }

        }

    } 

</script>

 

<!-- assuming that SqlDataSource1 is the datasource for my GridView -->

<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">

    <Columns>

        <asp:TemplateField>

            <AlternatingItemTemplate>

                <asp:CheckBox ID="CheckBox1" runat="server" />

            </AlternatingItemTemplate>

            <ItemTemplate>

                <asp:CheckBox ID="CheckBox1" runat="server" />

            </ItemTemplate>

            <HeaderTemplate>

                <asp:CheckBox ID="cbSelectAll" runat="server" Text="Select All"                                   OnClick="selectAll(this)" />

            </HeaderTemplate>

            <HeaderStyle HorizontalAlign="Left" />

            <ItemStyle HorizontalAlign="Left" />

        </asp:TemplateField>

    </Columns>

</asp:GridView>

 

Revision number 3, Wednesday, May 28, 2008 3:16:12 PM by adam.kahtava

Comments

Good approach to implement javascript ...

This is really an excellent stuff. Thx.

Nice poetry of javascript.

Instead of having the SelectAll function, I need to determine if ANY one of the checkboxes is selected, if so, then I will enable a 'Remove button'. If none of the checkboxes is selected, then 'Remove button' will be disabled. However, the problem is how can I found out the TOTAL number of checkboxes available as they are dynamically binded to the GridView control from the datasource. I'll appreciate if you can notify me at wyattwong@yahoo.com> if a solution is found.

I have solved my own problem with the following javascript code (no need server side code): asp:GridView ID="GridView1"" runat="server" AutoGenerateColumns="False" Width="500px"> Columns> asp:TemplateField> ItemTemplate> asp:CheckBox ID="chkSelected" runat="server" Checked="false" onclick="CheckStatus();" /> /ItemTemplate> HeaderStyle BackColor="#DDDDDD" BorderStyle="Solid" BorderWidth="1px" /> ItemStyle BorderStyle="Solid" BorderWidth="1px" HorizontalAlign="Left" Width="10px" /> /asp:TemplateField> /Columns> /asp:GridView> script type="text/javascript"> // Define the master page header mhr variable. var mhr = "ctl00_Content_"; function CheckStatus() { var checked = 0; for (i = 1; i = document.getElementById(mhr+"GridView1").rows.length; ++i) { if (i 10) index = "0" + i; else index = i; // Locate the chkSelected checkbox field chkSelected = document.getElementById(mhr+"GridView1_ctl"+ index + "_chkSelected"); if (chkSelected) { // chkSelected field exists if (chkSelected.checked) ++checked; } } // btnRemove is the Remove button // asp:Button ID="btnRemove" runat="server" Text="Remove"> if (checked > 0) document.getElementById(mhr+"btnRemove").disabled = false; else document.getElementById(mhr+"btnRemove").disabled = true; } /script>

Enjoyed it!

Shortcuts

Table of Contents

Top Wiki Contributors

(last 30 days)

  1. bmains (13)
  2. XIII (13)
  3. vik20000in (8)
  4. mbanavige (7)
  5. anas (5)
  6. tmorton (5)
  7. k_nitin_r (3)
  8. binoj7 (3)
  9. scott@elbandit.co.uk (2)
  10. sciguy65 (1)

Advertise Here