<asp:GridView ID="grid" runat="server" AutoGenerateColumns="false" GridLines="Horizontal"
OnPreRender="grid_PreRender">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<input type="checkbox" id="chkAll" />
</HeaderTemplate>
<ItemTemplate>
<input type="checkbox" id="chkItem" code='<%# Eval("Code") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Code" HeaderText="Code" HtmlEncode="true" />
<asp:BoundField DataField="Name" HeaderText="Name" HtmlEncode="true" />
<asp:BoundField DataField="Age" HeaderText="Age" HtmlEncode="true" />
<asp:BoundField DataField="Address" HeaderText="Address" HtmlEncode="true" />
</Columns>
</asp:GridView>
//全选/反选
$("#chkAll").click(function () {
$('#<%=grid.ClientID %> > tbody > tr > td > input:checkbox').attr("checked", this.checked);
});
//若所有tbody中的项都选中了,自动将表头中的chkAll选中.
$("#<%=grid.ClientID %> > tbody > tr > td > input:checkbox").click(function () {
//获取所有选中的checkbox元素
var expression1 = $("#<%=grid.ClientID %> > tbody > tr > td > input:checkbox:checked");
//获取所有checkbox元素
var expression2 = $("#<%=grid.ClientID %> > tbody > tr > td > input:checkbox");
var hasChecked = $(expression1).length == $(expression2).length;
$("#chkAll").attr("checked", hasChecked);
});
//获取表格中选中的值
$("#btnGetByGridCheckedElement").click(function () {
var selectedCodes = new Array();
var checkedItems = $("#<%=grid.ClientID %> > tbody > tr > td > input:checkbox:checked[@name$='chkItem']");
$.each(checkedItems, function () {
selectedCodes.push(this.code);
});
if (0 == selectedCodes.length) {
alert("没有选中任何项..");
return;
}
alert(selectedCodes.join(","));
});