Check/Uncheck checkboxes in GridView using javascript

Seen a lot of questions regarding how to check/uncheck CheckBoxes within a GridView control using JavaScript. So I thought to put it on my blog for quick reference for others and for myself. Following is the code:
------------------------------------------- .aspx code ---------------------------------------------
<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>

----------------------------------------- .vb file if VB.Net is the language ------------------------------------------
VB.Net Code

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 attribut for onclick event on the check box in the hearder 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


----------------------------------------- .cs file if C#.Net is the language ------------------------------------------
C#.Net Code


protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
        if ((e.Row.RowType == DataControlRowType.Header))
        {
            //adding an attribut for onclick event on the check box in the hearder 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 + "')");
        }
    }

21 Comments

  • What about other forms and unrelated checkboxes in the same page?

  • very precise and neat example/code. Straight to the point with min code.

    works good.

  • Hi Andrew,

    In this case which honestly speaking I rearely found you can make this addition to your javascript if statement

    if (frm.elements[i].type == "checkbox" && frm.elements[i].id.indexOf("") == 0)
    {
    frm.elements[i].checked = document.getElementById(id).checked;
    }

    As all the controls within GridView control will have a ClientID of GridView as the prefix. Now place as many check boxes as you want out side the grid view only the one inside it will be affected.

  • Hi Justin,

    According to my understanding I don't think it would be effective because you never know how many checkboxes will be created at runtime. As far as their ids are concerned it will be somthing like this

    GridView1_ctl01_CheckBox1

    here GridView1 is the client id for the GridView
    CheckBox1 is the id for the checkbox
    and GridView1_ctl01_CheckBox1 is the clientID for that particular check box. ctl01 will not remain same it will be ctl02, ctl03 for the next checkbox in the row.

    So if there are 50 rows you have to write 50 document.getElementById's assuming that you have fixed 50 rows and not more. I believe looping so far seems to be the more straight forward and easy approach.

  • Your gridview needs to callout the event OnRowDataBound="GridView1_RowDataBound"

  • next time let the credit goes where it belongs to

    here is the orginal link where he copied from:

    http://wiki.asp.net/page.aspx/281/check-uncheck-checkboxes-in-gridview-using-javascript/

  • The code is perfect.
    Thanks for posting this.

  • #nisarkhan probably what you see on wiki was also posted by me if i m not mistaken, and there are people who can make modifications in what you have posted by the way even on wiki i have not posted it i can say it was copied from here :).

    NOTE:
    for all the readers of the post I wrote a better way on check/unchecking checkboxes in gridview in this article http://www.codeproject.com/KB/grid/GridCheckBox.aspx

  • Hi Faraz,

    I would like to know how we can validate checkboxes in same row?
    Suppose i have two checkboxes in one row, one for 'Approve' and the other for 'Reject'.
    If either one is checked then the other one should be unchecked in the same row.
    How do we achieve this?
    Your help in this regard will be appreciated.

    Kindly send mail at imran.gummi@almarai.com

    Thanks and Regards,
    Mohammed Imran

  • I wrote a better version for the same task here http://www.codeproject.com/KB/grid/GridCheckBox.aspx

  • Super it's Working!!!!!!!!

  • Hi friend,
    Thanks a lot. it's working.

  • nice, really nice!

  • Thanks a lot dude you are the savior!

  • Thanks for you all. i used...
    //Check All Checkbox
    function jfn_CheckAll(Arg_Caller) {
    try {
    var chk_ChildCheckBox = document.getElementsByTagName('INPUT');
    for (var int_ctr = 0; int_ctr 0) {
    chk_ChildCheckBox.item(int_ctr).checked = Arg_Caller.checked;
    }
    }
    }
    }
    catch (e) {
    alert(e);
    }
    }

    -----------
    where my first column has a check box named 'Chk_Status' and i called this function from template header checkbox using 'OnClick="jfn_CheckAll(this)"'

    Thanks

  • Thanks
    Really helpful;)

  • Try This:

    var checked = false;



    function SelectAllCheckboxes() {
    e = document.forms[0].elements;
    //alert(e[i].type);
    for (i = 0; i < e.length; i++) {
    if (e[i].type == "checkbox") {
    if (checked) {
    e[i].checked = false;
    }
    else {
    e[i].checked = true;
    }
    }
    }

    if (checked == true) {
    checked = false
    }
    else {
    checked = true;
    }

    }

  • Hi,
    I have 2 checkboxes in 2 columns of the header. If I check the checkbox in second column it is selecting all the check boxes in first column and second column.(as it is checking all the elements in if statement).How to check only related colomns
    ie.first checkbox(column1) in header has to select only first columns and second checkbox(column 2) in header has to select only second columns.
    Please help me out
    Thank you very much.

  • @vamshipss

    You can try visiting one of my articles http://www.codeproject.com/Articles/24763/Check-uncheck-CheckBox-in-a-GridView-using-Javascr in which checkbox is taken from the column. I believe it will solve your problem.

    Faraz

  • how can i create mutually exclusive checkboxes using javascript.

  • It can be difficult to write about this subject.
    I think you did a great job though! Thanks for
    this!

Comments have been disabled for this content.