userqwert userqwert - 4 months ago 16
AngularJS Question

How to prevent multiple select in radio button?

I've this code:

<form name="quiz" ng-submit="quiz.answer(selected)">
<label>
<input type="radio" ng-model="selected" ng-value="true"> Red
</label>
<br/>
<label>
<input type="radio" ng-model="selected" ng-value="false"> Green
</label>
<br/>
<label>
<input type="radio" ng-model="selected" ng-value="false"> Blue
</label>
<br/>
<label>
<input type="radio" ng-model="selected" ng-value="false"> Yellow
</label>
<br/>
<input type="submit" id="submit" value="Submit" />
</form>


How do I prevent ALL of the false values from being selected at once if I click one?

Answer

As per my understanding you want to group the radio buttons such that one is selected at a time you can do it by adding name attribute in each radio button and give same name to all of them. So at time of submit you can get the value of selected variable in submit function call.

   <form name="quiz" ng-submit="quiz.answer(selected)">
         <label>
    <input type="radio" name="quizOption" ng-model="selected" ng-value="true">
    Red
  </label><br/>
  <label>
    <input type="radio" name="quizOption" ng-model="selected" ng-value="false">
    Green
  </label><br/>
  <label>
    <input type="radio" name="quizOption" ng-model="selected" ng-value="false">
    Blue
  </label><br/>
  <label>
    <input type="radio" name="quizOption" ng-model="selected" ng-value="false">
    Yellow
  </label><br/>
  <input type="submit" id="submit" value="Submit" />
</form>