我有多个复选框,一个复选框需要是selected.If,没有一个复选框被选中,表单应该通过验证error.Did,我错过了任何东西。有没有关于我如何实现这个行为的想法?我的.JS代码:
$scope.onCheckBoxSelected=function(){
var flag=false;
for(var key in selectedOptions){
console.log('Key -' +key +' val- '+selectedOptions[key]);
if(selectedOptions[key]){
flag=true;
}
}
if(!flag){
selectedOptions=undefined;
}
};下面是我的html代码:
<div class="grid">
<div class="col flex-10 mandatoryField" ng-class="{error: (!selectedOptions && formMissingFields)}">Hello please select atleast one</div>
<div class="col flex-2">
</div>
<div class="col flex-5">
<div style="padding-top: 2px">
<input type="checkbox" name="apple" title="Select type" value="apple" ng-model="apple" ng-change="onCheckBoxSelected()">apple
</input>
</div>
<div style="padding-top: 2px">
<input type="checkbox" name="orange" title="Select type" value="orange" ng-model="orange" ng-change="onCheckBoxSelected()">orange
</input>
</div>
<div style="padding-top: 2px">
<input type="checkbox" name="banana" title="Select type" value="banana" ng-model="banana" ng-change="onCheckBoxSelected()">banana
</input>
</div>
</div>
</div> 发布于 2017-07-07 00:22:00
您可以让它变得更简单,而不需要ngChange事件。
<div ng-class="{error: !apple && !orange && !banana">Hello please select atleast one</div>发布于 2017-07-07 00:25:08
使用AngularJS表单进行复选框验证是最佳实践-如果您打算扩展表单,它也会对您有所帮助。您必须重构您的代码才能使用此功能。
<ng-form name="myForm">
<span style="color:red;" ng-show="myForm.$invalid">Please select one</span>
<br />
<!-- your checkbox values will be in "choices" -->
<p ng-repeat="choice in choices">
<label class="checkbox" for="{{choice.id}}">
<input type="checkbox" value="{{choice.id}}" ng-click="updateQuestionValue(choice)" ng-model="choice.checked" name="group-one" id="{{choice.id}}" ng-required="value.length==0" /> {{choice.label}}
</label>
</p>
<input type="submit" value="Send" ng-click="submitSurvey(survey)" ng-disabled="myForm.$invalid" />
</ng-form>请参阅此fiddle -请注意,它使用了underscore.js。此外,this question可能会有所帮助。
https://stackoverflow.com/questions/44953833
复制相似问题