Search code examples
javascripthtmlangularjsangularjs-scopeangularjs-ng-disabled

How to make selecting a radio button required before submitting


I have a series of questions which have radio answer choices. I can't figure out how to use AngularJS validation to require the user to select one before clicking "Next". Below is my code:

EDIT: Please note that clicking "Next" gets the next question node from the controller depending on what choice was made. It's basically a dynamic questionnaire.

<form novalidate>
   <div class="radio" ng-repeat="answer in node.Answers">
      <input type="radio" name="answerGroup" ng-model="$parent.selectedAnswer" 
         value="{{answer.BranchId}},{{node.LeafId}},{{answer.Id}}"/> {{answer.Text}} 
   </div>
   <div>
      <input type="button" ng-click="previous()" value="Previous"/>
      <input type="button" ng-click="next(selectedAnswer)" value="Next"/>
   </div>
</form>

Solution

  • EDIT: Here is a working fiddle

    First give the form a name so that you can refer to it:

    <form name="myForm" novalidate>
    

    Next add the required attribute to the radio button:

    <input type="radio" name="answerGroup" required
        ng-model="$parent.selectedAnswer"
        value="{{answer.BranchId}},{{node.LeafId}},{{answer.Id}}"/>
    

    Then use ng-disabled to bind your next button's disabled property to the validity of the radio button:

    <input type="button" ng-click="next(selectedAnswer)" value="Next"
        ng-disabled="myform.answerGroup.$invalid" />