|
Note: This is an unedited contribution. If this article is inappropriate,
needs attention or copies someone else's work without reference then please
Report This Article
Introduction
Check/uncheck CheckBox control inside a GridView using javascript without postback. This article will give an idea on how to achieve this task.
Some sample code is provided under Using the code heading and complete code is available in the project download.
Background
(Forums are flooded with the questions about how to check/uncheck CheckBox control inside a GridView using javascript without postback.
How To’s:
In this article a GridView control is used. Inside the GridView control there are 3 fields. One template field and two are bound fields to display some sample data.
Inside the TemplateField a CheckBox control is placed in the HeaderTemplate (with ID cbSelectAll and Text Select All), ItemTemplate and AlternatingItemTemplate.
Using the code
Code that will be required to achieve this task.
Javascript that will be required to perform the Select All action is as follow:
<script type="text/javascript">
function SelectAll(id)
{
var grid = document.getElementById("<%= GridView1.ClientID %>");
var cell;
if (grid.rows.length > 0)
{
for (i=1; i<grid.rows.length; i++)
{
cell = grid.rows[i].cells[0];
for (j=0; j<cell.childNodes.length; j++)
{
if (cell.childNodes[j].type =="checkbox")
{
cell.childNodes[j].checked = document.getElementById(id).checked;
}
}
}
}
}
</script>
Code required to add an attribute of cbSelectAll CheckBox is as follow:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.GridView1.DataSource = FillDataTable();
this.GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" +
((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "')");
}
}
Before clicking the Select All CheckBox
After clicking the Select All CheckBox
| You must Sign In to use this message board. |
|
| | Msgs 1 to 12 of 12 (Total in Forum: 12) (Refresh) | FirstPrevNext |
|
 |
|
|
Hai, I have to upload a file to some Folder which is in Same LAN but another IP Address.My Problem is how to check whether the Folder is there or not? I have gone thru so many samples.......... but no use,Pls help me....
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
if i unselect any of the checkboxes in item template, header checkbox should unselect. If i select any one of the checkboxes in item template, it should check remaining checkboxeds are selected or not,if so it has check the header checkbox.Any help how to solve this.......
modified on Wednesday, September 10, 2008 4:12 AM
|
| Sign In·View Thread·PermaLink | 2.00/5 (1 vote) |
|
|
|
 |
|
|
Hi,
Try to add this javascript function in the script block
function checkStatus(id) { //get reference of GridView control var grid = document.getElementById("<%= GridView1.ClientID %>"); //variable to contain the cell of the grid var cell; var statusCheck = true;
if (grid.rows.length > 0) { //loop starts from 1. rows[0] points to the header. for (i=1; i<grid.rows.length; i++) { //get the reference of first column cell = grid.rows[i].cells[0]; //loop according to the number of childNodes in the cell for (j=0; j<cell.childNodes.length; j++) { //if childNode type is CheckBox if (cell.childNodes[j].type =="checkbox") { if (cell.childNodes[j].checked == false) { statusCheck = false; break; }
} } }
if (statusCheck) //change the status of the Select All checkbox document.getElementById(id).checked = true; else document.getElementById(id).checked = false; } }
modify you code behind like this
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { string cbSelectAllClientID = ""; if (e.Row.RowType == DataControlRowType.Header) { //Find the checkbox control in header and add an attribute ((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "')");
cbSelectAllClientID = ((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID; }
if (e.Row.RowType == DataControlRowType.DataRow) { //Here the checkboxes have an id cbStatus ((CheckBox)e.Row.FindControl("cbStatus")).Attributes.Add("onclick", "javascript:checkStatus('" + cbSelectAllClientID + "')"); } }
Faraz Shah Khan MCP, MCAD.Net, MCSD.Net, MCTS-Win/Web, MCPD-Web Blog
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
 |
|
|
Thanks for this ... very helpful and easy to understand.
But I can't seem to get it to work.
I have the page contained in a Masterpage. The script generated on the page is:
<script type="text/javascript"> //<![CDATA[ function SelectAll(GridName,SelectAll) { var grid = document.getElementById(GridName); var cell; if (grid.rows.length > 0) { for (i=1; i { cell = grid.rows[i].cells[0]; for (j=0; j { if (cell.childNodes[j].type =="checkbox") { cell.childNodes[j].checked = document.getElementById(SelectAll).checked; } } } } } //]]> </script>
and the grid part that makes use of the script is:
All seems to be fine ... what am I doing wrong. Please help.
Cheers. Ismail
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi Ismail,
So far the things you have placed seems fine, could you also please the code behind where you are calling the javascript function, also I would like to see the place where you are binding your GridView.
Faraz Shah Khan MCP, MCAD.Net, MCSD.Net Blog
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Thanks for looking at the problem.
The Grid is bound as follows:
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { LoadMandatesList(); } if (!Page.ClientScript.IsClientScriptBlockRegistered("MandateSelectAll")) { string strScript = Global.GetSelectAllScript(); Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MandateSelectAll", strScript, true); } //I have also tried it by putting this in the code-behind of the master page } protected void LoadMandatesList() { BindMandateList(0); } private void BindMandateList(int intNewPageIndex) { g_dtMandatesList = (GlobalVariables.g_AccessLevel == 1 || GlobalVariables.g_AccessLevel == 2) ? Mandate.GetMandatesList(g_AgencyID) : Mandate.GetMandatesList(g_AgencyID, g_AgentID); Global.BindGridView(ref grdMandatesList, g_dtMandatesList, intNewPageIndex); }
protected void grdMandatesList_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { string strGridName = grdMandatesList.ClientID, strSelectAll = ((CheckBox)e.Row.FindControl("chkSelectAll")).ClientID; string strJavascript = "javascript:SelectAll(" + strGridName + "," + strSelectAll + ")"; ((CheckBox)e.Row.FindControl("chkSelectAll")).Attributes.Add("onclick", strJavascript); } }
public static string GetSelectAllScript() { StringBuilder strRefreshScript = new StringBuilder(); strRefreshScript.Append("function SelectAll(GridName,SelectAll) \n"); strRefreshScript.Append("{\n"); strRefreshScript.Append("\t var grid = document.getElementById(GridName);\n"); strRefreshScript.Append("\t var cell;\n"); strRefreshScript.Append("\t if (grid.rows.length > 0)\n"); strRefreshScript.Append("\t {\n"); strRefreshScript.Append("\t\t for (i=1; i<grid.rows.length;> strRefreshScript.Append("\t\t\t for (j=0; j<cell.childnodes.length;> strRefreshScript.Append("\t\t\t\t {\n"); strRefreshScript.Append("\t\t\t\t\t cell.childNodes[j].checked = document.getElementById(SelectAll).checked;\n"); strRefreshScript.Append("\t\t\t\t }\n"); strRefreshScript.Append("\t\t\t }\n"); strRefreshScript.Append("\t\t }\n"); strRefreshScript.Append("\t }\n"); strRefreshScript.Append("}\n"); } }
Apologies for throwing all this code at you, but hope that you can find what could be wrong.
One this I also noticed is that from the ErrorConsol in Firefox I get this message:
Error: missing ; before statement Source File: javascript: Error: ctl00_ContentPlaceHolder1_grdMandatesList is not defined
Source Code: Error: ctl00_ContentPlaceHolder1_grdMandatesList is not defined
Thanks.
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi,
Just to test with I created a sample in which there is one MasterPage and one aspx page. I put the javascript in MasterPage and call it from the aspx page as shown in the following code and works fine.
Master Page:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> <script type="text/javascript"> function SelectAll(id, gridId) { //get reference of GridView control var grid = document.getElementById(gridId); //variable to contain the cell of the grid var cell; if (grid.rows.length > 0) { //loop starts from 1. rows[0] points to the header. for (i=1; i<grid.rows.length; i++) { //get the reference of first column cell = grid.rows[i].cells[0]; //loop according to the number of childNodes in the cell for (j=0; j<cell.childNodes.length; j++) { //if childNode type is CheckBox if (cell.childNodes[j].type =="checkbox") { //assign the status of the Select All checkbox to the cell checkbox within the grid cell.childNodes[j].checked = document.getElementById(id).checked; } } } } } </script> </head> <body> <form id="form1" runat="server"> <div> <asp:contentplaceholder id="ContentPlaceHolder1" runat="server"> </asp:contentplaceholder> </div> </form> </body> </html>
-----------------------------------------------------------------------------------
aspx Page:
<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" Title="Untitled Page" %> <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound"> <Columns> <asp:TemplateField> <AlternatingItemTemplate> <asp:CheckBox ID="cbSelectAll" runat="server" /> </AlternatingItemTemplate> <HeaderTemplate> <asp:CheckBox ID="cbSelectAll" runat="server" Text="Select All" /> </HeaderTemplate> <ItemTemplate> <asp:CheckBox ID="cbSelectAll" runat="server" /> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="ApplicationName" HeaderText="Application Name" /> <asp:BoundField DataField="ServerName" HeaderText="Server Name" /> </Columns> </asp:GridView> </div> </asp:Content>
-----------------------------------------------------------------------------------------------------------------
.cs File
public partial class Default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //Binding GridView with the datasource this.GridView1.DataSource = FillDataTable(); this.GridView1.DataBind(); } }
/// <summary> /// Method that will add few rows in a DataTable and returns a DataTable /// </summary> /// <returns>DataTable</returns> protected DataTable FillDataTable() { DataTable dt = new DataTable(); dt.Columns.Add("ApplicationID"); dt.Columns.Add("ApplicationName"); dt.Columns.Add("ServerName");
DataRow dr = dt.NewRow(); dr[0] = "1"; dr[1] = "Application 1"; dr[2] = "Server 1"; dt.Rows.Add(dr);
DataRow dr1 = dt.NewRow(); dr1[0] = "2"; dr1[1] = "Application 2"; dr1[2] = "Server 2"; dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow(); dr2[0] = "3"; dr2[1] = "Application 3"; dr2[2] = "Server 3"; dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow(); dr3[0] = "4"; dr3[1] = "Application 4"; dr3[2] = "Server 4"; dt.Rows.Add(dr3);
DataRow dr4 = dt.NewRow(); dr4[0] = "5"; dr4[1] = "Application 5"; dr4[2] = "Server 5"; dt.Rows.Add(dr4);
DataRow dr5 = dt.NewRow(); dr5[0] = "6"; dr5[1] = "Application 6"; dr5[2] = "Server 6"; dt.Rows.Add(dr5);
return dt; } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Header) { //Find the checkbox control in header and add an attribute ((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "','" + this.GridView1.ClientID + "')"); } } }
Now try to use this code and see if you are missing something in your earlier code.
Hope this will solve your problem.
Faraz Shah Khan MCP, MCAD.Net, MCSD.Net Blog
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Hi.
Sorry, didn't have time till today to work on this problem. I tested your code in my App, and it worked perfectly ... Now I just have to test it for all the gridviews in the application.
Thanks a stack...
Ismail ...
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
Change the if(cell.childNodes[j].lastChild.type == "checkbox" you checkbox is in a span html control try that.
Ronnie Peretz
|
| Sign In·View Thread·PermaLink | |
|
|
|
 |
|
|
farazsk11,
I've included some improvements to your JavaScript. It's less code and does the same thing. As well instead of passing an id to the SelectAll method, you could always just attach this method to the on click event of the "Select All" checkbox.
You can also strip a lot of the "{" and "}" brackets but because this editor doesn't take tabs into account, I've left them there.
Just my two cents, Nick 
<script type="text/javascript"> function SelectAll(id) { // use $get instead of document.getElementById if AJAX client-side framework is currently loaded. var selectAllCheckBox = document.getElementById(id); // I personally don't like adding client ids this way because it means this JavaScript // has to be rendered on the page as opposed to being cached in an external file. // I find it better to register a client-side script block on the page load or in the case // of ASP.NET AJAX enabled pages in the pre render phase. // Get a reference of GridView control var grid = document.getElementById("<%= GridView1.ClientID %>"); // Existentce check of objects to see if we can proceed. if (selectAllCheckBox && grid) { var inputs = grid.getElementsByTagName("input") // inputs.length > 0 is not necessary, just use inputs.length as your conditional // 0 results in false, so the > 0 is redundant. if (inputs.length) { //loop starts from 1. rows[0] points to the header. for (i=1; i<inputs.length; i++) //if childNode type is CheckBox if (inputs[i].type =="checkbox") { inputs[i].checked = selectAllCheckBox.checked; } } } } } </script>
|
| Sign In·View Thread·PermaLink | 5.00/5 (1 vote) |
|
|
|
 |
|
|
General News Question Answer Joke Rant Admin
|