Check all checkbox column in Datagrid through javascript

Also Check Out: My latest venture. http://loqly.me – a way for you to ask questions and get answers about local businesses around you. iTunes link: http://bit.ly/e5u4jv (only available in US for now)


Here is how to put a check all checkbox in the Column Header of the datagrid so that when the user clicks it all the checkboxes in all rows below also get checked. Also, the cool thing is that this will happen on the client side using javascript without any postbacks !

checkbox.jpg

Step 1: Add the checkbox column in your datagrid. see eg. below :

<asp:datagrid id=”dg1″ AutoGenerateColumns=”False” Width=”100%” Runat=”server”>
<Columns>
<asp:TemplateColumn>
<HeaderTemplate>
<input ID=”chkAll” type=”checkbox” onclick=”CheckAllDataGridCheckBoxes(‘chkItem’,this.checked)”>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID=”chkItem” Runat=”server”></asp:CheckBox>
   </ItemTemplate>
</asp:TemplateColumn>

Step 2:
<script lang=“javascript”>
function CheckAllDataGridCheckBoxes(aspCheckBoxID, checkVal)
{
re = new RegExp(‘:’ + aspCheckBoxID + ‘$’)  //generated control name starts with a colon
for(i = 0; i < Form1.elements.length; i++)
{
elm = document.forms[0].elements[i]
if (elm.type == ‘checkbox’)
{
if (re.test(elm.name))
elm.checked = checkVal
}
}
}
</script>

Thats it. Now, when you click a checkbox in the column header all checkboxes in that column will toggle without the page getting posted back.

Advertisements

40 thoughts on “Check all checkbox column in Datagrid through javascript

  1. Hi

    The above code is very useful to me but i have small doubt
    whats the importance of following statment ? .
    re = new RegExp(’:’ + aspCheckBoxID + ‘$’)

    can you mail me

    thanx and regards
    Murali

  2. The reason why you have to use new RegExp(….aspcheckboxid) is that we are looping through all form elements, but we only want to mess around with the Checkbox controls in every row of the datagrid. Also, we dont want to touch any other checkboxes which maybe on the page. Thats why we compare every checkbox ID to make sure that it is the correct checkbox.

  3. great code. thanks a lot

    do you have javascript function to delete data which the checkbox is checked?

    please guide me.

    thanks in advanced

  4. As far as my I know, it is not possible to delete a row in the datagrid using javascript. The reason would be that the viewstate will still think that the row is there (even if you delete it using javascript) and when it goes to the server for a roundtrip, the code will bomb. I will let you know if I find something though.

  5. hi…
    i hav a datagrid with a databound col(numeric value) & a template col containing combobox…in combobox i hav 2 values “pending” & “approved” and i also hav a textbox outside datagrid

    wat i want is when i change the combobox status to “approved” the corresponding values in databound col should be compared to textbox value and show appropriate msg….this should also be true for multiple “approved” selection(summation of all selected “approved” shud be equal to textbox value

    can u help…plzzz

  6. Ohhh…….This code is really helpful.
    Actually I had 3 datagrid on the same page,and I had this problem where all the checkboxes in this page was getting checked.

    This code helped me in solving the above problem.
    Thanks.

    Regards,
    Justin Samuel

  7. It does not work. The id of check boxes generated is different that used re = new RegExp(‘:’ + aspCheckBoxID + ‘$’) here. How it will work can u help me.

  8. Oh……..
    Really great.Its really helpful for every body who want to work with Datagrd without postback.

    Thanks
    Pranjit Kalita

  9. if RegExp(’:’ + aspCheckBoxID + ‘$’) is not working we can revised the function as. Try this it will work

    function CheckAllDataGridCheckBoxes(aspCheckBoxID, checkVal)
    {

    for(i = 0; i

  10. Hello Nishant Bhai
    I was searching for VB 6 help/code for datagrid having checkboxs.
    can u plz help me ; how I can make standalone application with such type of ActiveX component.

  11. if i have two colunm contains checkbox then it will check all check box when i clicked header plz reply …

  12. Chirag,

    If you observe the code carefully, I am passing the name of the checkbox to the function CheckAllDataGridCheckBoxes(‘chkItem’,this.checked)”>. So, it will only check the column that I want checked, not any other column.

  13. For 2.0 the code never gets passed the line:
    if (re.test(elm.name))

    can you help with this please? should the syntax be different for 2.0
    Thanks in advance

  14. For client script here is the code:

    function ChangeAllCheckBoxStates( checkVal )
    {
    for (var i = 0; i < CheckBoxIDs.length; i++)
    {
    document.getElementById(CheckBoxIDs[i].valueOf()).checked = checkVal;
    }
    }

    Please set the gridview properties as below:

    Set the databound event of gridview in c#:

    protected void GridView1_DataBound(object sender, EventArgs e)
    {
    CheckBox cbHeader = (CheckBox) GridView1.HeaderRow.FindControl(“chkAll”);
    cbHeader.Attributes[“onclick”] = “ChangeAllCheckBoxStates(this.checked);”;

    List ArrayValues = new List();
    ArrayValues.Add(String.Concat(“‘”, cbHeader.ClientID, “‘”));

    foreach (GridViewRow row in GridView1.Rows)
    {
    CheckBox cb = (CheckBox) row.FindControl(“chkItem”);

    ClientScript.RegisterArrayDeclaration(“CheckBoxIDs”, “‘”+cb.ClientID+”‘”);
    }
    CheckBoxIDsArray.Text = “” +”\n\r” +
    “” + “\n\r” +
    “”;

    }

    I have tested it and it is up and running!

  15. For client script here is the code:

    Please set the gridview properties as below:
    #asp:TemplateField>
    #HeaderTemplate>
    #asp:CheckBox runat=”server” ID=”chkAll” />
    #/HeaderTemplate>
    #ItemTemplate>
    #asp:CheckBox ID=”chkItem” Runat=”server”>#/asp:CheckBox>
    #/ItemTemplate>
    #/asp:TemplateField>

    #asp:BoundField />
    #/Columns>

    Set the databound event of gridview in c#:

    protected void GridView1_DataBound(object sender, EventArgs e)
    {
    CheckBox cbHeader = (CheckBox) GridView1.HeaderRow.FindControl(“chkAll”);
    cbHeader.Attributes[“onclick”] = “ChangeAllCheckBoxStates(this.checked);”;

    List#string> ArrayValues = new List#string>();
    ArrayValues.Add(String.Concat(“‘”, cbHeader.ClientID, “‘”));

    foreach (GridViewRow row in GridView1.Rows)
    {
    CheckBox cb = (CheckBox) row.FindControl(“chkItem”);

    ClientScript.RegisterArrayDeclaration(“CheckBoxIDs”, “‘”+cb.ClientID+”‘”);
    }
    CheckBoxIDsArray.Text = “#script type=’text/javascript’>” +”\n\r” +
    String.Concat(“var CheckBoxIDs = new Array(“, String.Join(“,”, ArrayValues.ToArray()), “);”) + “\n\r” + “#/script>”;

    }

    I have tested it and it is up and running!
    just replace # with relation operation smaller than.

  16. re = new RegExp(’:’ + aspCheckBoxID + ‘$’) this code is woriking in local system but when i upload in net its not working can u tell me why and which browser it will work correctly and its version

  17. hai this is fine

    but i want in different way

    i am having all checkboxes in every column of row

    if i check a checkbox in that row so all checkboxes in that column has to be checked

    i want this type of functionality

    if u help on this it will be grear help for me

    k

    bye

  18. Hi, I can’t write the complete code for you, but to check all columns in a particular row, you can try the following :

    Instead of doing a document.all.elements…you have to do TR.all or TR.getElementsByTagName(‘INPUT’) (use ‘this’ parameter to get current row’s TR object). The rest of the loop will remain pretty much the same.

    Hope this helps

  19. very nice article, thanks. It works for me. but i have a small problem to something related. Suppose i have user control checkInC.ascx instead of checkbox. But this control contains only a asp.checkbox, and i use it in datagrid as below..

    how can i control the asp.checkbox..to be checked if the checkbox is checked.

  20. i found the solution for that, you just have to enter the ID for the checkbox from user control and not the user control ID. Thanks

  21. I have 2 columns in a data grid which are check boxes. Each check box is in an in the of datagrid. I want to make these mutually exclusive.

    How can I achieve this ?

  22. I wonder if you could give some advice on a similar problem I am having. I have a datagrid on a webpage with several template columns. In one of these template columns is a checkbox, one on each row. I need to check whether or not each checkbox is checked in the datagrid, as well as get a list of the dates for each row if that row is checked using javascript. I have been unable to reference the checkbox value in the template column with javascript.

    Thanks in advance for any help rendered.

  23. M not able to delete all selected rows from datagrid when i checked header checkbox and all columns checkboxes are checked………………….plz give proper answer.

  24. This is not working for me, pls help me to solve this problem.

    function CheckAllDataGridCheckBoxes(aspCheckBoxID, checkVal)
    {
    re = new RegExp(’:’ + aspCheckBoxID + ‘$’) //generated control name starts with a colon
    for(i = 0; i < Form1.elements.length; i++)
    {
    elm = document.forms[0].elements[i]
    if (elm.type == ‘checkbox’)
    {
    if (re.test(elm.name))
    elm.checked = checkVal
    }
    }
    }

  25. It’s the first time I commented here and I must say you share us genuine, and quality information for bloggers! Good job.
    p.s. You have a very good template for your blog. Where did you find it?

    • I had same problem but in my case am setting textbox value not the checkbox value. Script works fine for 200 rows but if my rows are 1000 or more then javascript takes huge time as it runs for all controls.
      can i optimize this script to get only respective column ….. thks in advance 🙂 — vijay H.

  26. It is working fine at localhost, what when published to web server it does not work, check all check boxed checked, it does not select all check boes in datagrid. even there is no error.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s