簡體   English   中英

使復選框成為必需的AngularJS

[英]Make checkboxes required AngularJS

我有一個表單,用戶必須通過復選框回答問題。 復選框很少,我在表單中使用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>

知道如何解決這個問題嗎? 如果你可以工作小提琴那么棒。

試試這個工作演示:

 var myApp = angular.module('myApp',[]); myApp.controller('MyCtrl',function($scope) { }); 
 <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> 

如果要使用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> 

您可以使用數組執行此操作:

 var myApp = angular.module('myApp',[]); myApp.controller('MyCtrl',function($scope) { $scope.collection=[{ "Name": "IT"}, { "Name": "Design"}, { "Name": "Photoshop"}, { "Name": "Writing"}]; $scope.disableButton = true; $scope.doTheThings = function (item) { if (item.checked) $scope.disableButton = true; else $scope.disableButton = false; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="MyCtrl"> <ul> <li ng-repeat="item in collection"> <input type="checkbox" name="skills" ng-model="item.checked" ng-click="doTheThings(item)"> {{item.Name}} </li> </ul> <button ng-disabled="disableButton"> Submit </button> </form> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM