Disabling check according to selected quantity [closed]

0

I have a component that has an input: checkbox. This component is repeated several times on the screen. How do I block the checkbox, limiting my user to click a maximum of 3 checkboxes ie the user will only be able to click a maximum of 3 checkboxes.

    
asked by anonymous 09.04.2018 / 20:31

1 answer

1

You can do this with a javascript control by calling an event each time the user clicks a check to check the others. Example:

var app = angular.module('dmExemploApp', []);

app.controller('ctrlExemplo', function($scope) {

  $scope.limite = 3;
  $scope.total = 0;
  $scope.checks = [false, false, false, false, false, false];

  $scope.$watchCollection('checks', function(new_value) {
    $scope.total = 0;
    angular.forEach(new_value, function(value) {
      if(value) $scope.total++;
    });
  });

  $scope.reset = function(i) {
    $scope.checks = [false, false, false, false, false, false];
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-app="dmExemploApp"><div ng-controller="ctrlExemplo">
<p><input id="chk1" type="checkbox" value="1" ng-model="checks[0]" ng-disabled="total >= limite"> <label for="chk1">Primeiro</label></p>
<p><input id="chk2" type="checkbox" value="2" ng-model="checks[1]" ng-disabled="total >= limite"> <label for="chk2">Segundo</label></p>
<p><input id="chk3" type="checkbox" value="3" ng-model="checks[2]" ng-disabled="total >= limite"> <label for="chk3">Terceiro</label></p>
<p><input id="chk4" type="checkbox" value="4" ng-model="checks[3]" ng-disabled="total >= limite"> <label for="chk4">Quarto</label></p>
<p><input id="chk5" type="checkbox" value="5" ng-model="checks[4]" ng-disabled="total >= limite"> <label for="chk5">Quinto</label></p>
<p><input id="chk6" type="checkbox" value="6" ng-model="checks[5]" ng-disabled="total >= limite"> <label for="chk6">Sexto</label></p>
<p><button ng-click="reset()">Recomeçar</button></p>
</div></div>
    
09.04.2018 / 20:53