user3844782 user3844782 - 19 days ago 6
AngularJS Question

AngularJS Validating group of radio buttons and checkboxes in a form

I am trying to validate 2 sets of radio buttons and a set of checkboxes in a form. At least one item should be selected from each set before submitting form. I did like shown below but the button is not getting enabled when i select one from each set.

I also tried setting using "required" for the inputs and like "required !=
radioM" for the different sets , but nothing worked. Seems simple, but what i am doing wrong.

<form class="form-inline" name="myForm">
<div class="form-group">
<label class="radio-inline" >
<input name="sampleinlineradio" value="1" type="radio" ng-model="radioM"
ng-required="true" >Main1</label>
<label class="radio-inline">
<input name="sampleinlineradio" value="2" type="radio" ng-model="radioM"
ng-required="true" >Main2</label>
<label class="radio-inline">
<input name="sampleinlineradio" value="3" type="radio" ng-model="radioM"
ng-required="true" >Main3</label></div>

<div class="form-group">
<label ng-repeat="branch in branches" >
<input type="checkbox" name="selectedBranches[]" value="{{branch.value}}"
ng-model="branch.selected" ng-required="true" >{{branch.name}}
</label></div>

<div class="form-group">
<label class="searchlabel">
<input name="searchinlineradio" value="showComponentSearch" type="radio"
ng-model="value" ng-required="true">Search By C_Number</label>
<input type="text" ng-model="search" >

<label class="searchlabel">
<input name="searchinlineradio" value="showDateRangeSearch"
type="radio" ng-model="value" >Search By Time</label></div>

<input type="button" ng-click="fetchAll()" value="submit"
class="btn btn-success" ng-disabled="myForm.$invalid">
</form>


UPDATE
I added below code to the controller. Now what happens is the button get enabled when i select a radio from group1 and a checkbox from group2 without selecting a radio from last group. Also if i select a radio from group1 and a radio from group2 (button is still disabled) and then select checkbox the button gets enabled [(i.e.) if i change order it works fine].

In controller

$scope.branches= [ { name: 'B1', selected: false, value: '1'},
{ name: 'B2', selected: false, value: '2'},
{ name: 'B3', selected: false, value: '3'}
];
//added this
$scope.isOneSelected = function(){
return !$scope.branches.some(function(options){
return options.selected;
});
};

Answer

You can use required for all the fields and you are using bootstrap datepicker, for that you need to check the $scope variable as well, do something like this,

<div ng-if="value == 'showDateRangeSearch'">
  <input type="button" ng-click="fetchAllstats()" value="Generate Report" class="btn btn-success" ng-disabled="myForm.$invalid && !fromDate && !toDate">
</div>
<div ng-if="value == 'showComponentSearch'">
  <input type="button" ng-click="fetchAllstats()" value="Generate Report" class="btn btn-success" ng-disabled="myForm.$invalid">
</div>