【问题标题】:checkbox validation angularjs复选框验证angularjs
【发布时间】:2017-07-07 02:12:37
【问题描述】:

我有一个问题的多个复选框。至少需要选择一个复选框。如果没有一个复选框被选中,则应该通过验证错误。我错过了什么吗?关于如何实现这种行为的任何想法? 我的 .JS 代码:

$scope.onCheckBoxSelected=function(){

                            var flag=false;
                            for(var key in selectedOptions){
                                console.log('Key -' +key +' val- '+selectedOptions[key]);
                                if(selectedOptions[key]){
                                    flag=true;
                                }
                            }
                            if(!flag){
                                selectedOptions=undefined;
                            }
                        };

下面是我的html代码:

<div class="grid">
    <div class="col flex-10  mandatoryField" ng-class="{error: (!selectedOptions && formMissingFields)}">Hello please select atleast one</div>
    <div class="col flex-2">
    </div>
    <div class="col flex-5">

        <div style="padding-top: 2px">
            <input type="checkbox" name="apple" title="Select type" value="apple" ng-model="apple" ng-change="onCheckBoxSelected()">apple
            </input>
        </div>
        <div style="padding-top: 2px">
            <input type="checkbox" name="orange" title="Select type" value="orange" ng-model="orange" ng-change="onCheckBoxSelected()">orange
            </input>
        </div>
        <div style="padding-top: 2px">
            <input type="checkbox" name="banana" title="Select type" value="banana" ng-model="banana" ng-change="onCheckBoxSelected()">banana
            </input>
        </div>

    </div>

</div>                  

【问题讨论】:

    标签: javascript html angularjs checkbox


    【解决方案1】:

    你可以让它更简单,而不需要 ngChange 事件。

    <div ng-class="{error: !apple && !orange && !banana">Hello please select atleast one</div>
    

    【讨论】:

    • 谢谢..!!无需 ngChange 事件即可按预期工作
    【解决方案2】:

    使用 AngularJS 表单进行复选框验证是最佳实践 - 如果您打算扩展表单,它也会对您有所帮助。您必须重构代码才能使用此功能。

     <ng-form name="myForm">
        <span style="color:red;" ng-show="myForm.$invalid">Please select one</span>
        <br />
        <!-- your checkbox values will be in "choices" -->
        <p ng-repeat="choice in choices">
          <label class="checkbox" for="{{choice.id}}">
            <input type="checkbox" value="{{choice.id}}" ng-click="updateQuestionValue(choice)" ng-model="choice.checked" name="group-one" id="{{choice.id}}" ng-required="value.length==0" /> {{choice.label}}
          </label>
        </p>
        <input type="submit" value="Send" ng-click="submitSurvey(survey)" ng-disabled="myForm.$invalid" />
      </ng-form>
    

    看到这个fiddle - 请注意它使用underscore.js。此外,this question 可能会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-07
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 2016-09-11
      • 2015-05-23
      相关资源
      最近更新 更多