javascript限制所选择复选框的个数

<!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>
效果图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值