如何用js获取GridView中CheckBox 被选中的其它字段的内容?
我想实现 选中Gridview中的Checkbox后,利用js 获取被选中这一行的其他字段的数据。
------解决方案--------------------给个参考..
//aspx.cs
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
CheckBox chkSelect = (CheckBox)e.Row.FindControl( "chkSelect ");
chkSelect.Attributes.Add( "onclick ", "show ( ' " + e.Row.RowIndex + " ') ");
}
}
//aspx页添加脚本
function show(index)
{
var table = document.getElementById( "GridView1 ");
for(var i = 1; i < table.rows[0].cells.length; i++)
alert (table.rows[index + 1].cells[i].innerText);
return false;
}
------解决方案--------------------完整示例代码:
功能
1, 单击 checkbox 返回当前行值
2, 外部按钮获取所有选择行的值
<%@ Page Language= "C# " %>
<%@ Import Namespace= "System.Data " %>
<%-- http://community.csdn.net/Expert/TopicView3.asp?id=5653656 --%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN " "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<script runat= "server ">
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
LoadProductData();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Button btnHiddenPostButton = e.Row.FindControl( "btnHiddenPostButton ") as Button;
if (btnHiddenPostButton != null) {
e.Row.Attributes[ "onclick "] = String.Format( "javascript:document.getElementById( '{0} ').click() ", btnHiddenPostButton.ClientID);
// 额外样式定义
e.Row.Attributes[ "onmouseover "] = "javascript:this.style.background= 'red ' ";
e.Row.Attributes[ "onmouseout "] = "javascript:this.style.background= ' ' ";
e.Row.Attributes[ "style "] = "cursor:pointer ";
e.Row.Attributes[ "title "] = "单击选择当前行 ";
}
// 若希望将隐藏按钮单独放于一列,则设置此列隐藏,占位符 <cellIndex> 表示此列索引
//e.Row.Cells[ <cellIndex> ].Attributes[ "style "] = "display:none ";
}
void LoadProductData()
{
DataTable dt = CreateSampleProductData();
GridView1.DataSource = dt;
GridView1.DataBind();
}
#region sample data
static DataTable CreateSampleProductData()
{
DataTable tbl = new DataTable( "Products ");
tbl.Columns.Add( "ProductID ", typeof(int));
tbl.Columns.Add( "ProductName ", typeof(string));
tbl.Columns.Add( "UnitPrice ", typeof(decimal));
tbl.Columns.Add( "CategoryID ", typeof(int));
tbl.Rows.Add(1, "Chai ", 18, 1);
tbl.Rows.Add(2, "Chang ", 19, 1);
tbl.Rows.Add(3, "Aniseed Syrup ", 10, 2);
tbl.Rows.Add(4, "Chef Anton 's Cajun Seasoning ", 22, 2);
tbl.Rows.Add(5, "Chef Anton 's Gumbo Mix ", 21.35, 2);
tbl.Rows.Add(47, "Zaanse koeke