2015-07-28 95 views
1

我想要遵循所有的例子,但我没有任何运气。我使用jquery验证检查创建了一个plunker。我只需要允许1个复选框被选中。 ​​如何限制与角或jquery的复选框选择

<body ng-controller="MainCtrl"> 
    <div class="form-group fg-line"> 
    <label for="companies" class="control-label"><b>Role Type</b></label><br /> <br /> 
<table> 
    <tr ng-repeat="model in userRoles"> 
     <td> 
     <div class="checkbox m-b-15"> 
      <label> 
      <input id="rolebox" class="check" type="checkbox" ng-model="model.RoleId"> 
      <i class="input-helper"></i> 
       {{model.Name}} 
     </label> 
     </div> 
    </td> 
</tr> 
    </table> 
     </div>  
     <script> 
     var checked = [], 
      $check = $('.check').change(function() { 
      if (this.value == -1 && this.checked) { 
       $check.not(this).prop('disabled', true).prop('checked', false); 
       checked = []; 
      } 
      else { 
       $check.prop('disabled', false); 
       checked.push(this); 
       checked = $(checked) 
       checked.prop('checked', false).slice(-2).prop('checked', true); 
      } 
     }); 

+3

你为什么不只是使用无线电,而不是一个复选框,为复选框通常表明多选择,其中如收音机是单身。不要让这个问题脱轨,而只是一个建议。 – mikeswright49

+0

好点。没有想到这个 – texas697

+0

或者使用'if($(“:checkbox:checked”)。length> 1){//多于一个选择}' – lshettyl

回答

2

我需要只允许1个选择复选框到组外。

正如您在其中一个评论中提到的那样,您应该真的使用单选按钮来达到这个目的,因为它们是针对这种情况的。如果您必须使用复选框,则可以执行以下操作。

$(document).on("change", ".check", function() { 
    var $allCheckboxes = $(".check"); 
    $allCheckboxes.prop("disabled", false); 
    this.checked && $allCheckboxes.not(this).prop("disabled", true); 
}); 

Your updated plunker

2

分配相同name值的所有复选框。例如:

<input name="nm" id="rolebox1" class="check" type="checkbox" ng-model="model.RoleId"> 
<input name="nm" id="rolebox2" class="check" type="checkbox" ng-model="model.RoleId"> 
+0

你可以在笨蛋中展示吗?没有在我的机器上工作 – texas697