spaceholder
spaceholder

Reputation: 171

Limit number of checkboxes checked inside ng-repeat

So I have javascript code that checks how much checkboxes is checked. It works well except that when I hit 4 checkboxes it disables all checkboxes not only unchecked (you can see it on image below). Thank you!

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> 

dasdas you can see the checked checkboxes are also disabled.

Upvotes: 0

Views: 703

Answers (2)

artemnih
artemnih

Reputation: 4209

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'])
<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>

Upvotes: 1

Zorken17
Zorken17

Reputation: 1896

You need to itterate through the array of checkboxes again after you selected more than 3, and see wich checkbox is selected and disable only them.

What you are doing now is to disable all checkboxes when you have checked more than 3. device.selectedf = true;

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

So I have a little hard time reading your code, but this might be a solution in the right direction for you:

$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;
        }
    }
} 

Hope it helps. /Zorken17

Upvotes: 1

Related Questions