Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS : How to disable checkboxes after specified amount is selected?

I have checkboxes within loop like below:

 <li ng-repeat="item in items">
      <h2>  {{item.better}}</h2>
      <span>{{item.startTime}}</span>
      <b>   {{item.lengthTime}}</b>
      <input type="checkbox" checklist-model="item.winner" checklist-value="item">
 </li>

I want to set limit so that users could only select maximum 50 checkboxes and not more than that out of (no. of total items in the list i.e 100 or 200 etc.).

How do we accomplish that using angular js ?

Help would be really appreciated.

Thank you.

like image 861
Meet Avatar asked May 26 '14 17:05

Meet


People also ask

How to disable checkbox in Angular JS?

We will use the Angular JS directive named ng-disabled to disable the button by unchecking the box. Please refer to AngularJS ng-disabled Directive. The ng-disabled directive is used to enable or disable the HTML elements.

How can I disable mat checkbox condition?

You can use the [disable] attribute your input[type="checkbox"] tag. For larger, more complex forms I highly recommend using a reactive form. With a reactive form, you can use [disabled]="condition" where the condition is something like whateverCheckbox.


2 Answers

FIDDLE

$scope.checkChanged = function(item){
    if(item.winner) $scope.checked++;
    else $scope.checked--;
}

and

 <input type="checkbox" ng-model="item.winner" ng-change="checkChanged(item)" ng-disabled="checked==limit && !item.winner"/>

this keeps track of checked with ng-change and disables them if the limit is reached and the checkbox is not checked.

not using $watch because of the possibility of ~200 checkboxes.

edit: sorry forgot to click update on fiddle, it should work now. Also note that limit is set to 4 with $scope.limit = 4;

like image 82
Quad Avatar answered Oct 28 '22 09:10

Quad


you could ask for the number of items and use the ng-disabled

<input type="checkbox" ng-disabled="!item.value && items.length > 50" />

Update:

as mentioned in the comments, the answer is not correct. But i think you got (and other guys who answered) the right idea how to accomplish what you need. I think, the necessary information for you is to use ng-disabled.

I like Aperçu answer most :)

like image 1
Luke Avatar answered Oct 28 '22 09:10

Luke