在复选框上添加最大`checkable`限制

时间:2017-04-13 03:40:38

标签: javascript jquery

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

  1. 变量让我们说maxSelections可用于控制最大可选复选框
  2. 到达maxSelections后,应禁用页面上的其他复选框
  3. 此时,不应禁用已检查过的内容,因为用户必须从此处取消选中某项内容以选择其他可用复选框
  4. ps我已经提到了这个JSFiddle但是不能让第二点工作 在此先感谢您的帮助

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

1 个答案:

答案 0 :(得分:0)

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

  

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

     

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

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

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

这是一个能够满足您需求的片段:

&#13;
&#13;
  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
        }
      });
&#13;
<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>
&#13;
&#13;
&#13;

相关问题