I have an array of checkbox controls added in index.html
. I want to check if atleast one checkbox is checked when the user clicks on submit button. I tried the below code, but it does not seem to work.
In index.html:
<form name="mainForm" id="createForm" ng-submit="mainForm.$valid && add()" novalidate="">
<div >
<label>Delivery Method</label>
</div>
<div ng-repeat="method in deliveryMethods">
<input type="checkbox" id="{{method.id}}"
value="{{method.value}}" name="deliveryMethod[]" ng-model="method.selected"
ng-click="toggleSelection(method.value)" ng-required="!someSelected">
{{method.value}}
</div>
</div>
<span style="color:red" ng-show="submitted == true && !someSelected">Delivery is required</span>
<input type="submit" value="Submit" ng-click="submitted=true" />
In the controller.js file,
$scope.deliveryMethods = [{
"id": 1,
"value": "Test-up",
selected: true
}, {
"id": 2,
"value": "Test Two",
selected: false
}, {
"id": 3,
"value": "Test Three",
selected: false
}];
$scope.toggleSelection = function toggleSelection(deliveryMethods) {
var idx = $scope.deliverySelection.indexOf(deliveryMethods);
if (idx > -1) {
$scope.deliverySelection.splice(idx, 1);
} else {
$scope.deliverySelection.push(deliveryMethods);
}
someSelected();
};
$scope.someSelected = true;
function someSelected() {
$scope.someSelected = false;
for (var i = 0; i < $scope.deliveryMethods.lenght; i++) {
if ($scope.deliveryMethods[i].selected == true) {
$scope.someSelected = true;
return false;
}
}
}
I would like to check, if atleast one checkbox is checked, when user clicks on submit button. If no checkbox is selected, then show a span with custom message. How to fix this? Thanks