javascript Angular.js 至少需要一个复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26979303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular.js required at least one checkbox
提问by KingKongFrog
I wouldn't be surprised if this is a duplicate however I can't find anything simple along the lines of what I need.
如果这是重复的,我不会感到惊讶,但是我找不到任何符合我需要的简单内容。
All I need is the user to be required to choose at least one checkbox but I'm baffled how to accomplish 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
回答by khalid13
<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
回答by BeingDev
HTML
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
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 fiddle : http://jsfiddle.net/fodyyskr/
JS小提琴:http: //jsfiddle.net/fodyyskr/