【问题标题】:Why can't I limit the number of checked checkboxes? [duplicate]为什么我不能限制选中复选框的数量? [复制]
【发布时间】:2018-05-23 17:25:42
【问题描述】:

我有 4 个复选框,我想将选择限制为最多 3 个。我的谷歌搜索是否找到了一个有效的:

http://jsfiddle.net/vVxM2/

这是我的代码:

<html>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
        var limit = 3;
        $('input.ko_chk').on('change', function(evt) {
           if($(this).siblings(':checked').length >= limit) {
               this.checked = false;
           }
        });
    </script>
    <body>
        <input type="checkbox" class="ko_chk" name="first" value="1"><br>
        <input type="checkbox" class="ko_chk" name="second" value="2"><br>
        <input type="checkbox" class="ko_chk" name="third" value="3"><br>
        <input type="checkbox" class="ko_chk" name="fourth" value="4">
    </body>
</html>

还是……

那么,我的代码有何不同?

【问题讨论】:

标签: jquery html checkbox


【解决方案1】:

您只需要将 jQuery 脚本设为自己的标签,并将您的脚本放在您要选择的标签之后。

<input type="checkbox" class="ko_chk" name="first" value="1"><br>
<input type="checkbox" class="ko_chk" name="second" value="2"><br>
<input type="checkbox" class="ko_chk" name="third" value="3"><br>
<input type="checkbox" class="ko_chk" name="fourth" value="4">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
  var limit = 3;
  $('input.ko_chk').on('change', function(evt) {
    if ($(this).siblings(':checked').length >= limit) {
      this.checked = false;
    }
  });
</script>

【讨论】:

  • 在执行$('input.ko_chk')的时候,DOM还没有准备好,所以选择器没有细化任何元素。
  • @t.niese -- 好点,已修复。另外,我将其转换为 Community Wiki。请随时解决其他问题。
猜你喜欢
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 2011-02-27
  • 2013-09-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多