<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>javascript限制所选择复选框的个数</title>
</head>
<body>
<form id="form1" name="form1" method="post" action=""style="margin-top:150px;">
<table width="230" height="109" border="0" align="center" style="font-family:Georgia, 'Times New Roman', Times, serif; font-weight:bold; color:#F60;" >
<tr>
<td width="48" height="33"><input type="checkbox" name="one" id="one" onClick="countChoices(this)" /><!--点击监听,用countChoices()计数-->
1
<label for="one"></label></td>
<td width="59"><input type="checkbox" name="two" id="two" onClick="countChoices(this)" />
2</td>
<td width="51"><input type="checkbox" name="three" id="three" onClick="countChoices(this)"/>
3</td>
<td width="54"><input type="checkbox" name="four" id="four" onClick="countChoices(this)"/>
4</td>
</tr>
<tr>
<td height="34"><input type="checkbox" name="five" id="five" onClick="countChoices(this)"/>
5</td>
<td><input type="checkbox" name="six" id="six" onClick="countChoices(this)"/>
6</td>
<td><input type="checkbox" name="seven" id="seven" onClick="countChoices(this)"/>
7</td>
<td><input type="checkbox" name="eight" id="eight" onClick="countChoices(this)"/>
8</td>
</tr>
<tr>
<td height="34"><input type="checkbox" name="nine" id="nine" onClick="countChoices(this)" />
9</td>
<td><input type="checkbox" name="ten" id="ten" onClick="countChoices(this)"/>
10</td>
<td colspan="2" style="font-family:'宋体'; font-size:12px; color:#F60;">最多选4个!</td>
</tr>
</table>
</form>
</body>
<SCRIPT LANGUAGE="JavaScript">
function countChoices(obj) {
max = 4;/*设置最多选择的个数*/
one = obj.form.one.checked;
two = obj.form.two.checked;
three = obj.form.three.checked;
four = obj.form.four.checked;
five = obj.form.five.checked;
six = obj.form.six.checked;
seven = obj.form.seven.checked;
eight = obj.form.eight.checked;
nine = obj.form.nine.checked;
ten = obj.form.ten.checked;
count = (one ? 1 : 0) + (two ? 1 : 0) + (three ? 1 : 0)+ (four ? 1 : 0)+ (five ? 1 : 0)+ (six ? 1 : 0)+ (seven ? 1 : 0)+ (eight ? 1 : 0)+ (nine ? 1 : 0)+ (ten ? 1 : 0);/*累加,每选一个就累加一个数*/
if (count > max) {/* 判断是否大于max*/
alert("对不起,你最多只能选择" + max + "个项目!");
obj.checked = false;
}
}
//-->
</script>
</html>
效果图: