限制在ng-repeat中选中的复选框数

时间:2015-11-12 07:19:38

标签: javascript jquery html angularjs checkbox

所以我有javascript代码检查检查了多少复选框。它运行良好,但当我点击4个复选框时,它会禁用所有复选框,而不仅仅是未选中(您可以在下面的图片中看到它)。谢谢!

JAVASCRIPT

$scope.checkedb= function (unit, device, unitt){
  unitt.showcb = !unitt.showcb;

 numOfCh = 0;
  for (var i = 0 ; i < unit.length; i ++){
    if (unit[i].showcb == true){
      numOfCh ++;
    }

    if (numOfCh > 3){
      device.selectedf = true;
    }
  }
}

HTML

<div ng-repeat="unit in data[unitIndex].units" ng-if="unit.users_ID == tvw.id">

        <td class="footable-visible" > 

           <input type="checkbox" ng-disabled="device.selectedf" ng-click="checkedb(data[unitIndex].units, device, unit)">

        </td> 
</div> 

dasd正如您所看到的,复选框也被禁用。

2 个答案:

答案 0 :(得分:1)

选择3个以上后,您需要再次检查复选框数组,并选中复选框并选中它们。

您现在正在做的是在检查超过3时禁用所有复选框.mevice.selectedf = true;

if (numOfCh > 3){
  if ( "this checkbox is checked" ){
    do this on this checkbox => device.selectedf = true;
  }
}

所以我在阅读您的代码时遇到了一些困难,但这可能是您正确方向的解决方案:

$scope.checkedb = function (unit, device, unitt){
  unitt.showcb = !unitt.showcb;

  var numOfCh = 0;
  for (var i = 0 ; i < unit.length; i ++){
    if (unit[i].showcb == true){
      numOfCh ++;
    }

    if (numOfCh > 3){
      disableCheckboxes();
      return;
    }
  }
}

function disableCheckboxes(unit, device, unitt){
     unitt.showcb = !unitt.showcb;
    for (var i = 0 ; i < unit.length; i ++){
        if (unit[i].showcb == false){
            unit[i].device.selectedf = true;
        }
    }
} 

希望它有所帮助。 / Zorken17

答案 1 :(得分:1)

&#13;
&#13;
var app = angular.module('app', []);
app.controller('DomReadyCtrl', function($timeout, $scope){
		var maxChk = 4;
    $scope.units = [
    	{ checked: false },
        { checked: false },
        { checked: false },
        { checked: false },
        { checked: false },
        { checked: false },
        { checked: false }
    ];
$scope.checkedb = function() {
      return $scope.units.filter(
      	function(unit) {return unit.checked; }).length >= maxChk;
    };
});
angular.bootstrap(document.body, ['app'])
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="DomReadyCtrl">
  <div ng-repeat="unit in units">
    <td class="footable-visible" > 
      <input ng-model="unit.checked" ng-disabled="!unit.checked && checkedb()" type="checkbox" />{{unit.name}}
    </td> 
  </div> 
</div>
&#13;
&#13;
&#13;