JS实现对gridview中的checkbox的选中个数记录,并在页面刷新时保持checkbox的状态
案例描述:为防止checkbox勾选时页面刷新,给客户更好的体验,要求实现ASPX上实时记录checkbox的选中个数。因为页面其它查询时要刷新,所以还要记录checkbox的勾选状态。
实现代码:
ASPX页面核心代码:
<asp:Label ID="lblCount" runat="server" ForeColor="#C04000"></asp:Label>
<asp:GridView ID="GridView1" runat="server" >
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chb" runat="server" ToolTip='<%# Eval("QST_CODE") %>' onclick="checkboxCount()" OnCheckedChanged="chb_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
</asp:GridView>
<asp:HiddenField ID="hfQstCode" runat="server" />
JS代码:
<script language="javascript" type="text/javascript">
function checkboxCount()
{
var controlIndex;
var element;
var numberofControls;
numberofControls = document.forms[0].length;
var checkBoxCount = 0;
for (controlIndex=0; controlIndex<numberofControls; controlIndex++)
{
element = document.forms[0][controlIndex];
if (element.type == "checkbox")
{
if(element.checked == true)
{
checkBoxCount ++;
}
}
}
var tt = document.getElementById("lblCount");
tt.innerHTML = "已选数量:" + checkBoxCount;
}
</script>
CS核心代码:
//OnCheckedChanged事件,记录选中的checkbox的ToolTip
protected void chb_CheckedChanged(object sender, EventArgs e)
{
string strQstCode = "";//用来记录选中的checkbox的ToolTip
foreach (GridViewRow row in GridView1.Rows)
{
if (((CheckBox)row.Cells[0].Controls[0].FindControl("chb")).Checked)
{
strQstCode += (((CheckBox)row.Cells[0].Controls[0].FindControl("chb")).ToolTip + ",");
}
}
hfQstCode.Value = strQstCode;//存入Hidden中
}
//页面刷新时,选中之前已勾选的checkbox in gridview1
if (hfQstCode.Value != "")
{
string[] QstCodeArr = hfQstCode.Value.Split(',');
CheckBox cbid = new CheckBox();
for (int i = 0; i < QstCodeArr.Length; i++)
{
for (int j = 0; j < GridView1.Rows.Count; j++)
{
CheckBox cbidObj = (CheckBox)this.GridView1.Rows[j].Cells[0].FindControl("chb");
if (cbidObj.ToolTip == QstCodeArr[i].ToString())
{
cbidObj.Checked = true;
}
}
}
}
点评:
1、OnCheckedChanged事件,不要设置AutoPostBack,不然会刷新页面了;
2、ToolTip='<%# Eval("QST_CODE") %>',是绑定的数据字段,用与区分并标记checkbox,也可以用任何自加的属性,比如:xid,pid;
3、如果将<asp:CheckBox ID="chb"> 换成<input type="checkbox" >,则CS代码中的CheckBox类型,应对应成:HtmlInputCheckBox