日期:2014-05-18  浏览次数:20814 次

checkbox选择数量问题
比如一个checkbox有5项,我想控制用户只能选择2项,当选择超过两项时,就会把最早一次选择的项取消。应该怎么做?

谢谢各位,如果您会的话,麻烦附上主要的代码

------解决方案--------------------
刚才的代码有些错误,修改了一下
<html>
<head>
<SCRIPT>
var cbArray = new Array();
function clickBox()
{
var obj = event.srcElement;
if (obj.checked)
{
cbArray.push(obj);alert(cbArray.length);
if (cbArray.length > 2)
{
var temp = cbArray.shift();
temp.checked = false;
}
}
else
{
for (var i = 0; i < cbArray.length; i++)
{
if (cbArray[i] == obj)
{
cbArray[i].checked = false;
cbArray.splice(i, 1);
}
}
}
}

</SCRIPT>
</head>
<body onload= " ">
<form>
<input type= "checkbox " name= "cb " value= "1 " onclick= "clickBox() ">
<input type= "checkbox " name= "cb " value= "2 " onclick= "clickBox() ">
<input type= "checkbox " name= "cb " value= "3 " onclick= "clickBox() ">
<input type= "checkbox " name= "cb " value= "4 " onclick= "clickBox() ">
<input type= "checkbox " name= "cb " value= "5 " onclick= "clickBox() ">
</form>
</body>
</html>