我有一个表单,用户必须通过复选框回答问题。复选框很少,我在表单中使用 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
现在我希望复选框是必需的,因此用户至少要从“技能”复选框中选中 1 个框。
我试过放置 required
标签,但它似乎不起作用。
我像这样使用 AngularJS 来验证我的表单
<button ng-disabled="myForm.$invalid">Submit</button>
知道如何解决这个问题吗?如果您可以使用 fiddle ,那就太好了。
最佳答案
如果你想使用 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>
关于javascript - 使复选框成为必需的 AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41977970/