javascript - 将复选框限制为仅三个复选框 - 如何?

标签 javascript jquery forms checkbox zurb-foundation

我的表单上有很多复选框。我需要将总数限制为选中的三个复选框,不能再多了。我的代码可以工作,但我刚刚将我的表单升级到基础自定义表单,我的脚本不再工作,我无法让它工作。

如何重写脚本才能工作?

这是当前脚本:

$(function(){
  var max = 3;
  var checkboxes = $('input[type="checkbox"]');

  checkboxes.click(function(){
    var $this = $(this);
    var set = $this.add($this.prevUntil('label')).add($this.nextUntil('label'));
    var current = set.filter(':checked').length;
    return current <= max;
  });
});

这里是表单代码:

<label>Effects <span class="red">required</span></label>
   <label for="CAT_Custom_365571_0"><input type="checkbox" value="Creative" id="CAT_Custom_365571_0" name="CAT_Custom_365571" style="display: none;">
<span class="custom checkbox"></span> Creative</label>
   <label for="CAT_Custom_365571_1"><input type="checkbox" value="Euphoric" id="CAT_Custom_365571_1" name="CAT_Custom_365571" style="display: none;">
<span class="custom checkbox"></span> Euphoric</label>
   <label for="CAT_Custom_365571_2"><input type="checkbox" value="Uplifted" id="CAT_Custom_365571_2" name="CAT_Custom_365571" style="display: none;">
<span class="custom checkbox"></span> Uplifted</label>
   <label for="CAT_Custom_365571_3"><input type="checkbox" value="Energetic" id="CAT_Custom_365571_3" name="CAT_Custom_365571" style="display: none;">
<span class="custom checkbox"></span> Energetic</label>
   <label for="CAT_Custom_365571_4"><input type="checkbox" value="Lazy" id="CAT_Custom_365571_4" name="CAT_Custom_365571" style="display: none;">
<span class="custom checkbox"></span> Lazy</label>
   <label for="CAT_Custom_365571_5"><input type="checkbox" value="Focused" id="CAT_Custom_365571_5" name="CAT_Custom_365571" style="display: none;">
<span class="custom checkbox"></span> Focused</label>
<!-- MORE CHECKBOXES -->

显然,当我更改表单时,我破坏了脚本。我该如何解决这个问题?

最佳答案

我会考虑包装(如果您还没有)复选框并使用委托(delegate)来提高性能。

假设元素已被 id 为 wrap 的元素包裹:

$(function () {
    var max = 3;
    $('#wrap').on('click', 'input[type="checkbox"]', function(){
        return $(this).closest('#wrap').find(':checked').length <= max;
    });
});

这是一个 fiddle

关于javascript - 将复选框限制为仅三个复选框 - 如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19943829/

相关文章:

Javascript 复选框切换 div 隐藏显示

javascript - background.html 与 background.js - chrome 扩展

javascript - 在插入到 div 时应用样式

PHP POST 不发送所有输入

javascript - Bootstrap Dropdown 使下拉箭头改变方向

javascript - 在页面加载之前使用 Firebug 调试 DOM 突变

javascript - 如何添加输入值

php - PHP 中的 HTML 表单

javascript - Nodejs 页面在 POST 后未重定向

javascript - Mongo在插入后查找文档