简体   繁体   English

如何在提交前选择需要的单选按钮

[英]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".我不知道如何使用 AngularJS 验证来要求用户在单击“下一步”之前选择一个。 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>

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:接下来将required属性添加到单选按钮:

<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:然后使用ng-disablednext按钮的disabled属性绑定到单选按钮的有效性:

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

Look below, using ng-show to display an error message should neither radio button be clicked.看下面,使用 ng-show 显示错误消息,不应单击两个单选按钮。

                          <label for="dateofbirth">
                            <span>Are you the primary cardholder?</span>
                            </label>
                            <ul>
                              <li>
                                <label for="yes">
                                  <input type="radio" id="yes" name="cardholder" ng-model="user.cardholder" value="yes" required/>
                                  Yes
                                </label>
                              </li>
                              <li>
                                <label for="no">
                                  <input type="radio" id="no" name="cardholder" ng-model="user.cardholder" value="no" required/>
                                  No
                                </label>
                              </li>
                            </ul>
                        </fieldset>
                        <span class="error" ng-show="myForm.cardholder.$error.required && submitted == true"><i class="fa fa-exclamation-circle"></i>Please select an answer.</span>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM