Angular.js needs at least one checkbox

I would not be surprised if this is a duplicate, but I cannot find anything simple according to what I need.

All I need is for the user to select at least one checkbox, but I don’t understand how to do this.

<input type="checkbox" ng-model="myForm.first" /> First <br /> <input type="checkbox" ng-model="myForm.second" />Second <br /> <input type="checkbox" ng-model="myForm.third" /> Third 
+5
source share
2 answers
 <input type="checkbox" ng-model="myForm.first" ng-required="myForm.first || myForm.second || myForm.third" /> First <br /> <input type="checkbox" ng-model="myForm.second" ng-required="myForm.first || myForm.second || myForm.third"/>Second <br /> <input type="checkbox" ng-model="myForm.third" ng-required="myForm.first || myForm.second || myForm.third"/> Third 
+6
source

HTML

 <div ng-app="myApp" ng-controller="myCrtl as myForm"> <input type="checkbox" ng-required="myForm.selectedOptions" ng-model="myForm.selectedOptions.first" ng-change="myForm.onCheckBoxSelected()" /> First <br /> <input type="checkbox" ng-required="myForm.selectedOptions" ng-model="myForm.selectedOptions.second" ng-change="myForm.onCheckBoxSelected()"/>Second <br /> <input type="checkbox" ng-required="myForm.selectedOptions" ng-model="myForm.selectedOptions.third" ng-change="myForm.onCheckBoxSelected()"/> Third<br/> <span style="color:red;" ng-if="!myForm.selectedOptions ">Required</span> </div> 

Js

 angular.module('myApp',[]) .controller('myCrtl',function(){ var myForm=this; myForm.onCheckBoxSelected=function(){ var flag=false; for(var key in myForm.selectedOptions){ if(myForm.selectedOptions[key]){ flag=true; } } if(!flag){ myForm.selectedOptions = undefined; } }; }); 

JS script: http://jsfiddle.net/fodyyskr/

0
source

Source: https://habr.com/ru/post/1207060/


All Articles