复选框验证最大值无效



我试图有多个复选框,然后选择了一个检查不超过3个的js脚本。我在网上找到了代码,所有的评论都表明它有效,但它在我的机器上不起作用。没有错误,但什么也没发生。这是我的标题:

<SCRIPT type="text/javascript">

    function KeepCount() {
        var NewCount = 0
        if (document.form1.one.checked)
        { NewCount = NewCount + 1 }
        if (document.form1.two.checked)
        { NewCount = NewCount + 1 }
        if (document.form1.three.checked)
        { NewCount = NewCount + 1 }
        if (document.form1.four.checked)
        { NewCount = NewCount + 1 }
        if (document.form1.five.checked)
        { NewCount = NewCount + 1 }
        if (document.form1.six.checked)
        { NewCount = NewCount + 1 }
        if (document.form1.seven.checked)
        { NewCount = NewCount + 1 }
        if (document.form1.eight.checked)
        { NewCount = NewCount + 1 }

        if (NewCount == 3) {
            alert('Pick Just Two Please')
            document.form1; return false;
        }
    }

然后在我的身体里,我有了id=form1的表格,上面有这些复选框:

     <label>
      <INPUT TYPE="checkbox" NAME="one" onClick="return KeepCount()"> One
  </label>
</div>
  <div class="checkbox">
  <label>
    <INPUT TYPE="checkbox" NAME="two" onClick="return KeepCount()"> two
  </label>
</div>

etc

就像我说的,什么都没发生。没有错误,但没有js。

感谢

您可以使用Jquery,只需更少的行数,请参阅fiddlehttp://jsfiddle.net/m89k0u95/1/

$('input[type=checkbox]').on('change', function (e) {
    if ($('input[type=checkbox]:checked').length > 3) {
        $(this).prop('checked', false);
        alert("allowed only 3");
    }
});

最新更新