Home / ASP.NET Wiki / Javascript / Check/Uncheck checkboxes in GridView using JavaScript

Check/Uncheck checkboxes in GridView using JavaScript

 Rate It (51)

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(invoker) {

        // 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 invoker (our calling element) as the reference 

               //  for our checkbox status

                myElement.checked = invoker.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 4, Thursday, February 04, 2010 7:08:35 AM 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!

Thats gr8 its works

nice!

Nice Article, Very use ful

it is superb i have seen so many java script codes for this pupose , but this is the best, You rock man, Thanxx a ton for solving my Problem

I appreciate the javascript snippet for checking all checkboxes in an asp.net gridview. We could check if any row is checked by checking the status of the checkbox in the row, on a button click from code behind. This is really useful in many tasks like deleting a checked row, and like.

script type="text/javascript"> function SelectDeselectAll(invoker) { var gv = document.getElementById("gv_Attendees"); var gvInputs = gv.getElementsByTagName("input"); for (var i = 0; i gvInputs.length; i++) { var node = gvInputs[i]; if (node.type == "checkbox" && node != null) { node.checked = invoker.checked; } } } function GridViewCheckBoxChange() { var Allselect = true; var gv = document.getElementById("gv_Attendees"); var gvInputs = gv.getElementsByTagName("input"); for (var i = 0; i gvInputs.length; i++) { var node = gvInputs[i]; if (node.type == "checkbox" && !node.checked) { Allselect = false; break; } } if (document.getElementById("ChkBoxAll") != null || document.getElementById("ChkBoxAll") == 'undefined') { document.getElementById("ChkBoxAll").checked = Allselect; } }

Commentor Vivek.Kumar, I owe lunch! I have spent days reading blog after blog of non-working javascript, but this did the trick! The second method isn't working, but I suspect that is because the ChkBoxAll input element is not checked so that Allselect is always false. I'll do some testing and post my findings!

Hello, great example. But what if there are some checkboxes (outside) the datalist which shouldn't be checked? How can this be solved. i hope to hear some.

i use the second example, forgot to mention that.

I believe this javascript function will select all the checkboxes which are outside GridView too. for (i=0;ifrm.elements.length;i++) { if (frm.elements[i].type == "checkbox") { frm.elements[i].checked = document.getElementById(id).checked; } } Here you are checking all the checkboxes those are found on the form.

I believe this javascript function will select all the checkboxes which are outside GridView too. for (i=0;ifrm.elements.length;i++) { if (frm.elements[i].type == "checkbox") { frm.elements[i].checked = document.getElementById(id).checked; } } Here you are checking all the checkboxes those are found on the form.

good article, but it much easier if you use jQuery

how can i use an asp button instead of checkbox in the same way (no post back) OnClick="selectAll(this)"

Hi, can any tell me why do u have both alternatingitemtemplate and itemtemplate for defining checkbox in datagrid?? Won't itemtemplate alone suffice ??

Shortcuts

Table of Contents

Top Wiki Contributors

(last 30 days)

  1. abiruban (1)