5

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
0

2 Answers 2

6
<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
Sign up to request clarification or add additional context in comments.

3 Comments

I tried this approach and found that this required me to select none or all of the checkboxes. In the case that none is checked, ng-required is false for all of them, making validation succeed. If only first is checked, all checkboxes becomes required which causes the validation to fail. If all is checked, all is required, and validation succeeds.
Using !(myForm.first || myForm.second || myForm.third) seems to work fine however.
and if you have 20 checkboxes? this solution is good only if you have just a few
0

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 fiddle : http://jsfiddle.net/fodyyskr/

2 Comments

This isn't the correct use of ng-required. Your example can be implemented without ng-required like so: jsfiddle.net/yzjugv90
@britter that is awesome!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.