【问题标题】:Add a max `checkable` restriction on checkbox [duplicate]在复选框上添加最大“可检查”限制[重复]
【发布时间】:2017-04-13 11:54:06
【问题描述】:

假设我在页面上有 10 个复选框。我正在寻找一些非常具体的行为:

  1. 一个变量,比如maxSelections 可用于控制最大可选复选框
  2. 达到maxSelections 后,页面上的其他复选框应禁用
  3. 此时,不应禁用已选中的选项,因为用户必须从此处取消选中某些内容才能选择其他可用复选框

ps 我已经提到了这个JSFiddle,但不能让第 2 点起作用 在此先感谢您的帮助

var limit = 3;
$('input.single-checkbox').on('change', function(evt) {
   if($(this).siblings(':checked').length >= limit) {
       this.checked = false;
   }
});

【问题讨论】:

  • edit您的问题直接在问题正文中显示相关代码。除了链接的副本,请参阅this question(其中others)。
  • 我已经参考了您提到的问题,并说明了为什么我无法使用它提供的解决方案。很抱歉没有在我的问题中包含 JS
  • 你没有在你的问题中引用另一个问题,你只是链接到一个小提琴,但无论如何我链接到的另一个问题有解决同一问题的方法,包括关于禁用另一个问题的部分复选框。检查accepted answer - 点击处理程序中只需要两行代码(或者如果你不使用工作变量,你可以在一行中完成)。

标签: javascript jquery


【解决方案1】:

我们可以使用伪类来获取复选框的状态

:checked :选择当前选中的所有复选框

:not(:checked) :选中所有当前未选中的复选框

一旦我们有了这两个状态,我们就可以使用下面的 jQuery 语法来设置复选框的disabled 属性

$(<checkboxElememt>).prop('disabled', <true/false>);

这里有一个 sn-p 可以满足您的需求:

  var maxSelections = 3

$('input[type="checkbox"]').change(function() {
      var currentCount = $('input[type="checkbox"]:checked').length // Here we can get the number of checkboxs checked
        // :checked pseudo selects all teh checkboxes that are checked

      if (currentCount >= maxSelections) {
        $('input[type="checkbox"]:not(:checked)').prop('disabled', true); // :not(:checked) pseudo is used to select and disable all unchecked checkbox
        } else {
          $('input[type="checkbox"]').prop('disabled', false); // Else, let's enable all the checkboxes
        }
      });
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>

<div>
  <input type="checkbox" name="op1" id="op1" />
  <label for="op1">Option 1</label>
</div>
<div>
  <input type="checkbox" name="op2" id="op2" />
  <label for="op2">Option 2</label>
</div>
<div>
  <input type="checkbox" name="op3" id="op3" />
  <label for="op3">Option 3</label>
</div>
<div>
  <input type="checkbox" name="op4" id="op4" />
  <label for="op4">Option 4</label>
</div>

<div>
  <input type="checkbox" name="op5" id="op5" />
  <label for="op5">Option 5</label>
</div>

<div>
  <input type="checkbox" name="op6" id="op6" />
  <label for="op6">Option 6</label>
</div>

【讨论】:

  • 感谢伪类的解释。我会做同样的研究
猜你喜欢
  • 1970-01-01
  • 2013-01-05
  • 1970-01-01
  • 2019-08-04
  • 2013-12-09
  • 1970-01-01
  • 1970-01-01
  • 2018-11-30
  • 1970-01-01
相关资源
最近更新 更多