日期:2014-05-16  浏览次数:20422 次

共有四个复选框,当有两个选中,在点击第三个时,提示只能选两个。怎么实现?
如题

------解决方案--------------------
<head>
<title> Untitled Page </title>
<script type= "text/javascript ">
function cktest(ckvalue)
{
p=0;
var ck=document.getElementsByName( "test ");
for(i=0;i <ck.length;i++)
{
if(ck[i].checked) p++;
}
if(p> =3)
{
alert( "!!! ");
ck[ckvalue-1].checked=false;
}
}
</script>
</head>
<body>
<form>
<input type= "checkbox " id= "test " value= "1 " onclick= "cktest(this.value) " />
<input type= "checkbox " id= "test " value= "2 " onclick= "cktest(this.value) " />
<input type= "checkbox " id= "test " value= "3 " onclick= "cktest(this.value) " />
<input type= "checkbox " id= "test " value= "4 " onclick= "cktest(this.value) " />
</form>
</body>
</html>


不好意思~

我实在想不出怎么取消特定的选择...所以就用了value
应该少通用性了...
------解决方案--------------------
<script language= "javascript ">
function chkbox(elm)
{var obj=document.getElementsByName( "cbox ");
var num=0;
for (i=0;i <obj.length ;i++ )
if (obj[i].checked )
num+=1;
if (num> 2)
{alert( "最多可以选择两个! ");
elm.status=false;
}
}
</script>

<input type= "checkbox " name= "cbox " value=1 onclick= "chkbox(this); ">
<input type= "checkbox " name= "cbox " value=2 onclick= "chkbox(this); ">
<input type= "checkbox " name= "cbox " value=3 onclick= "chkbox(this); ">
<input type= "checkbox " name= "cbox " value=4 onclick= "chkbox(this); ">
------解决方案--------------------
<script language= "javascript ">
function chkbox(elm)
{var obj=document.getElementsByName( "cbox ");
var num=0;
for (var i=0;i <obj.length ;i++ )
if (obj[i].checked )
num+=1;
if (num> 2)
{alert( "最多可以选择两个! ");
elm.status=false;
}
}
</script>

<input type= "checkbox " name= "cbox " value=1 onclick= "chkbox(this); ">
<input type= "checkbox " name= "cbox " value=2 onclick= "chkbox(this); ">
<input type= "checkbox " name= "cbox " value=3 onclick= "chkbox(this); ">
<input type= "checkbox " name= "cbox " value=4 onclick= "chkbox(this); ">

------解决方案--------------------
<script language= "JavaScript " type= "text/javascript ">
var ichk=0;
function chksel(chk,sel){
if(ichk==2){
if(chk.checked){
alert( "最多只能选中两个! ");
chk.checked=false;
return null;
}
}
ichk+=(chk.checked?1:-1);
document.getElementById(sel).style.visibility=(chk.checked? "visible ": "hidden ");