Recently, I encountered a problem during development that the customer requested not to have many options, but these items can only be selected at most 2 items. If more than 2 items are selected, there will be no refresh and the user will be prompted that you have selected too many and one of them will be randomly deleted. I searched a lot of articles online but couldn't find any relevant examples. So I took great pains to write one myself and now share it with everyone. I am! I hope experts can give me more valuable advice.
It’s actually very simple. The first step is CheckBoxListText.aspx
<HEAD>
<TITLE>CheckBoxList instance</TITLE>
</HEAD>
<SCRIPT language="JavaScript">
function SetCheckBoxState(str)
{
o = document.getElementsByTagName("INPUT")
//o = from1.cbYyjslscly;
var val=0;
for(i=0;i<o.length;i++)
{
if(o[i].type=="checkbox" && o[i].checked && o[i].name==str)
{
//alert(o[i].value)
val = val + 1;
}
if(val > 2)
{
alert('The items you select can only be within 2!')
o[i].checked=false;
return;
}
}
//alert(val)
}
</SCRIPT>
</head>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:CheckBoxList id="CheckBoxList1" runat="server">
<asp:ListItem Value="NET">NET</asp:ListItem>
<asp:ListItem Value="JAVA">JAVA</asp:ListItem>
<asp:ListItem Value="VB">VB</asp:ListItem>
</asp:CheckBoxList>
</form>
</body>
</html>
checkBoxList1.Attributes.Add("OnClick","SetCheckBoxState('CheckBoxList1');");
in the background management file
and it's OK!