使复选框成为必需的AngularJS

时间:2017-02-01 10:56:55

标签: javascript html angularjs checkbox

我有一个表单,用户必须通过复选框回答问题。复选框很少,我在表单中使用AngularJS来验证它。基本验证是填写所有必填字段。

以下是我的示例代码:

<input type="checkbox" name="skills"> IT
<input type="checkbox" name="skills"> Design
<input type="checkbox" name="skills"> Photoshop
<input type="checkbox" name="skills"> Writing

现在我希望从#34;技能&#34;中获取复选框。复选框用户至少选中1框

我已尝试使用required标记,但它似乎无法正常工作。

我正在使用AngularJS来验证我的表单

<button ng-disabled="myForm.$invalid">Submit</button>

知道如何解决这个问题吗?如果你可以工作小提琴那么棒。

3 个答案:

答案 0 :(得分:2)

试试这个有用的演示:

&#13;
&#13;
var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl',function($scope) {
    
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
    <form name="checkBoxForm">
       <input type="checkbox" name="skills" ng-model="IT">IT
       <input type="checkbox" name="skills" ng-model="Design">Design
       <input type="checkbox" name="skills" ng-model="Photoshop">Photoshop
       <input type="checkbox" name="skills" ng-model="Writing">Writing

    <button ng-disabled="!IT&&!Design&&!Photoshop&&!Writing">Submit</button>
  </form>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

如果要使用ng-disabled =“myForm。$ invalid”

进行验证

  var app = angular.module('myModule', []);

        app.controller("myController", function ($scope) {
            $scope.choices = [{"name":"IT"},{"name":"Design"},{"name":"Technology"}];
            $scope.checkBoxArray = [];
            $scope.validate = function (value) {
                if ($scope.checkBoxArray.indexOf(value) == -1){
                    $scope.checkBoxArray.push(value);
                }
                else {
                    $scope.checkBoxArray.splice($scope.checkBoxArray.indexOf(value), 1);
                }
            }
        });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="myModule">
  <body ng-controller="myController">
<ng-form name="myForm">
    <span  ng-repeat="choice in choices">
        <input type="checkbox" name="skills" ng-required="checkBoxArray.length==0" ng-model="choice.checked" ng-change="validate(choice.name)">
        {{choice.name}}
    </span>
</ng-form>
<button ng-disabled="myForm.$invalid">Submit</button>
</body>
</html>

答案 2 :(得分:0)

您可以使用数组执行此操作:

autocomplete="off"
<?php if(!is_page('[YOUR PAGE ID]')) { ?>
    YOUR SIDEBAR CODE GOES HERE
<?php } ?>