嵌套在gridview中checkbox实现单选功能(js实现)
一.html控件
function SignCheck(cbox)
{
var obj = document.getElementsByTagName("input");
for (var i=0; i < obj.length; i++)
{
if(obj[i].type == "checkbox")
{
obj[i].checked = false;
}
var sid = cbox.id;
document.getElementById(sid).checked = true;
}
}
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<input id="Checkbox1" type="checkbox" name="ck" onclick="SignCheck(this);" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
二. ASP.NET控件
<script language="javascript" >
var ClickNum=0;//判断同一checkbox连续点击次数
var PreCheckboxID="";//记录点击checkbox的ID
//listId为控制checkbox的范围
//SelectRadio是点击checkbox自己
function SignCheck(listId,SelectCheckBox)
{
///判断是否连击同一个checkbox
if(PreCheckboxID==SelectCheckBox.id)
{
ClickNum = ClickNum + 1;
}
else
{
PreCheckboxID = SelectCheckBox.id;
ClickNum = 0;
}
//找到控制范围
var GridViewableSearchList=document .getElementById(listId);
//找到控制范围下所有input
var objs=GridViewableSearchList.getElementsByTagName("input");
//找到控制范围下所有checkbox并都变为false
for(var i = 0; i < objs.length; i++)
{
if(objs[i].type.toLowerCase() == "checkbox" )
objs[i].checked = false;
}
var SelectCheckBoxId=SelectCheckBox.id;
//如果连击次数为奇次checked为true偶次为false
if(ClickNum%2!=1)
{
document.getElementById(SelectCheckBoxId).checked = true;
}
else
{
document.getElementById(SelectCheckBoxId).checked = false;
}
}
</script>
<div align ="center" id="DivGridview">
<asp:GridView ID="gvBmxmlb" runat="server" >
<Columns>
<asp:TemplateField>
<HeaderTemplate >请选择</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkBox1" runat="server" onclick="SignCheck('DivGridview',this);"/>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" Width="45px" />
<HeaderStyle HorizontalAlign="Center" Width="45px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>