0

On an angularJS application I have a <form> with a group of radio buttons, I want to force the user to select an option before he validates the form.

Here a simplify version of my HTML code :

  <form name="myForm">
    <label ng-repeat="option in options">
      {{option.name}}
      <input type="radio" name="animalOptions" value="option.id" required>
    </label>
    <button type="submit" ng-disabled="!myForm.$valid">
      SUBMIT
    </button>
    <h1>
    {{myForm.$valid}}
    </h1>
  </form>

I reproduced my issue in this example :

JSfiddle

Why does it prints true instead of false ?

2 Answers 2

1

You need to set ng-model to keep the selected value, e.g. $scope.selected (required needs ng-model to work). Also a function is needed to set the model on every click. Validation can be done like this:

 <label ng-repeat="option in options">
    {{option.name}}
    <input type="radio" name="animalOptions" value="option.id" ng-model="selected" ng-click="toggle(option.id)" ng-required="!selected">
  </label>

ng-required="!selected" ensures that user has selected an option Check this example: fiddle example

Sign up to request clarification or add additional context in comments.

Comments

0

You need ng-model to set validity of your form input(s). And use

required

like this in Angular way :

ng-required="true"

Something like this :

<form name="testForm" ng-submit="yourSubmitFunction();" novalidate>
    <input type="radio" name="radio" ng-model="rr" value="optionA" ng-required="true"/> optionA
    <input type="radio" name="radio" ng-model="rr" value="optionB" /> optionB
    <button type="submit" >Submit</button>
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.