应该是挺简单的代码, 记录一下分享.
首先最直接的想法就是使用循环, 用局部变量记录已选的checkbox, 达到最大值就将余下的checkbox都禁止选择, 例如以下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>JS限制checkbox复选框多选</title>
<script language="javascript" type="text/javascript">
function onCheckBox(checkbox)
{var items = document.getElementsByName("item");var maxChoices = 3;var flag = 0;for(var i=0; i<items.length; i++){if(items[i].checked){flag ++;}}if(flag >= maxChoices){for(var k=0; k<items.length; k++){if(!items[k].checked){items[k].disabled = true;}}}else{for(var p=0; p<items.length; p++){if(!items[p].checked){items[p].disabled = false;}}}
}function onSubmitVote()
{var items = document.getElementsByName("item");var choices = 0;var maxChoices = 3;for(var j=0; j<items.length; j++){if(items[j].checked){choices ++;}}if(choices == 0){alert("请选择选项再提交");}else if(choices > maxChoices){alert("选择选项不能超过 "+ maxChoices + "个");}else{alert("提交成功");}
}</script>
</head>
<body >
JS限制checkbox复选框多选
<br><br><input type="checkbox" value="value1" name="item" onClick="onCheckBox(this);"/> 选项一
<br>
<input type="checkbox" value="value2" name="item" onClick="onCheckBox(this);"/> 选项二
<br>
<input type="checkbox" value="value3" name="item" onClick="onCheckBox(this);"/> 选项三
<br>
<input type="checkbox" value="value4" name="item" onClick="onCheckBox(this);"/> 选项四
<br>
<input type="checkbox" value="value5" name="item" onClick="onCheckBox(this);"/> 选项五
<br><br><input type="button" id="submit_vote" name="submit_vote" value="提交" onClick="onSubmitVote()" /></body>
</html>
效果是没问题, 但通常第一想法都是比較粗糙的, 好的东西须要加以雕琢. 上面用的的是局部变量, 所以每次进入js的onCheckBox()都是新的变量, 还要循环几次, 但换成全局变量, 每次进入, flag的值都是继续上次操作的值, 那么能够降低循环的次数了. 针对该部分做改动, 例如以下:
<script language="javascript" type="text/javascript">
var maxChoices = 3;
var flag = 0;function onCheckBox(checkbox)
{var items = document.getElementsByName("item");//var maxChoices = 3;//var flag = 0;if(checkbox.checked){flag ++;}else{flag --;}if(flag < maxChoices){for(var i=0; i<items.length; i++){if(!items[i].checked){items[i].disabled = false;}}}else{for(var i=0; i<items.length; i++){if(!items[i].checked){items[i].disabled = true;}}}}function onSubmitVote()
{var items = document.getElementsByName("item");var choices = 0;//var maxChoices = 3;for(var j=0; j<items.length; j++){if(items[j].checked){choices ++;}}if(choices == 0){alert("请选择选项再提交");}else if(choices > maxChoices){alert("选择选项不能超过 "+ maxChoices + "个");}else{alert("提交成功");}
}</script>
这样效果是一样的, 但循环就少一次.