功能需求
1, 單擊 checkbox 返回當前行值
2, 外部按鈕擷取所有選擇行的值
實現說明
參見主要代碼,代碼為自說明式。
原文地址:http://www.cnblogs.com/Jinglecat/archive/2007/07/15/818967.html
主要代碼
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkItem1" runat="server" onclick="if(this.checked) alert(getRowValue(this))" />
<%--OR--%>
<%--<input type="checkbox" id="chkItem2" onclick="if(this.checked) alert(getRowValue(this))" />--%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProductName" >
<ItemTemplate><%# Eval("ProductName") %></ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" />
</Columns>
</asp:GridView>
<script type ="text/javascript">
/**
返回 chk 所在行的儲存格值
@param chk 表示行中的 input type=check 對象
*/
function getRowValue(chk)
{
//debugger;
// if(sender.checked) { // 根據實際情況,決定是否進行選中狀態判斷
var tblRow = chk.parentNode.parentNode;
// 改變 tblRow.cells[<cellIndex>] 中預留位置 <cellIndex> 訪問不同儲存格
//return tblRow.cells[1].innerText + ", " + tblRow.cells[2].innerText;
return tblRow.cells[1].innerHTML + ", " + tblRow.cells[2].innerHTML;
// }
}
/**
返回指定 grdId 中所有選中行的儲存格值
@param grdId 表示 GridView/DataGrid 用戶端識別碼,實際上他們均呈現為 <table />
@param chkIdPart 表示待處理 input type=check 控制項的 ID 中的部分,考慮行中可能存在多個 checkbox, 通過此參數可以準確確定目標
*/
function getAllRowValue(grdId, chkIdPart)
{
//debugger;
var tbl = document.getElementById(grdId);
var chkList;
var txt = "";
/* 方法1
for(var i = 0; i < tbl.rows.length; i++) { // 遍曆行
chkList = tbl.rows[i].getElementsByTagName("input"); // 返回當前行內嵌的所有 input 控制項
for(var j = 0; j < chkList.length; j++) {
// 多條件準確確定目標 checkbox
if(chkList[j].type == "checkbox" && chkList[j].checked && chkList[j].id.indexOf(chkIdPart) > -1) {
txt += getRowValue(chkList[j]) + "\n";
break;
}
}
}*/
/* 方法2 */
chkList = tbl.getElementsByTagName("input"); // 返回表內嵌的所有 input 控制項
for(var j = 0; j < chkList.length; j++) {
// 多條件準確確定目標 checkbox
if(chkList[j].type == "checkbox" && chkList[j].checked && chkList[j].id.indexOf(chkIdPart) > -1) {
txt += getRowValue(chkList[j]) + "\n";
}
}
return txt;
}
</script>