2017-04-13 55 views
-1

比方说,我在页面上有10个复选框。我正在寻找非常具体与行为的东西:在复选框上添加最大`可检查`限制

  1. 变量假设maxSelections可以用来控制最大可选复选框达到maxSelections
  2. 后,页面上的其他复选框都应该被禁用
  3. 在这个时候,已经检查那些不应该被禁用的用户必须拥有从取消选中的东西在这里的选项,选择其他可用的复选框

PS我refered这个JSFiddle,但不能g ^等点-2是工作 预先感谢帮助

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

请编辑您的问题,直接在问题主体中显示相关代码。除了链接的副本外,请参阅[此问题](http://stackoverflow.com/questions/19001844/how-to-limit-the-number-of-selected-checkboxes)(其中[others](http:/ /stackoverflow.com/questions/14463238/limit-number-of-checkboxes-allowed-to-be-checked))。 – nnnnnn

+0

我已经引用了你提到的问题,并说明了为什么我遇到了它提供的解决方案问题。对不起,没有在我的问题中包括JS –

+0

你没有在你的问题中引用其他问题,你只是链接到一个小提琴,但无论如何,我链接到的其他问题已解决同一问题,包括部分禁用其他复选框。检查[接受的答案](http://stackoverflow.com/a/2966456/615754) - 在点击处理程序中只需要两行代码(或者如果您不使用工作变量)。 – nnnnnn

回答

0

我们可以利用伪类来获得的复选框

状态:检查:选择所有复选框当前已签

:没有(:选中):选择当前未签

所有复选框

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

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

这里的disabled属性的一个片段,它回答你所需要的:

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>

+0

感谢您对伪类的解释。我会做同样的研究 –