Disabling check according to selected quantity

Asked

Viewed 88 times

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 at most 3 checkboxes IE, the user will only be able to click at most 3 checkboxes.

inserir a descrição da imagem aqui

  • 3

    places the code snippet to facilitate

1 answer

1


You can do this with a javascript control, calling an event each time the user clicks a check to verify 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>

<div ng-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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.