user9326447
user9326447

Reputation: 99

Radio button checked status is not getting retrived

I want my formData to say which radio button is selected.Basically if its 1st radio button then it should be set to true if deselected it should be false. Currently with my below code model is not getting set. I tried using ng-value but then it didn't work. This is what i tried

Basically, I want model data to set to true based on checked status.

Html Code

                            <div class="radio">

                                <input type="radio" id="typeRadio1" name="optradio" ng-model="formData.selectedType.perm" ng-change="isRadioSelected('typeRadio1')" required><label for="typeRadio1">301 PERM</label>
                                <input type="radio" id="typeRadio2" name="optradio" ng-model="formData.selectedType.temp" ng-change="isRadioSelected('typeRadio2')" required><label for="typeRadio2">302 TEMP</label>
                            </div>

app.js

        $scope.formData = {}
        $scope.isRadioSelected = function(s) {
            if (document.getElementById(s).checked) { $scope.formData.selectedType.perm = true; }
            else { $scope.formData.selectedType.perm = false;}

            if (document.getElementById(s).checked) { $scope.formData.selectedType.temp = true; }
            else { $scope.formData.selectedType.temp = false;
}                
        }

Upvotes: 0

Views: 51

Answers (1)

Maher
Maher

Reputation: 2547

When you have checkbox you don't need ng-value because you will get true/false but checkbox also have unique ng-model but all Radio has same name with ng-value

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

app.controller("ctrl", function($scope){
  
  $scope.checkboxSelected = function(item){
    console.log(item)
  }
  
 $scope.radioSelected = function(){
    console.log($scope.form.radio)
  }

})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  checkbox1 - {{form.checkbox1}}
  <input type="checkbox" ng-change="checkboxSelected(form.checkbox1)" ng-model="form.checkbox1"/>
  
  checkbox1 - {{form.checkbox2}}
  <input type="checkbox" ng-change="checkboxSelected(form.checkbox2)" ng-model="form.checkbox2"/>
  
  
  <hr>
  
  
  radio - {{form.radio}}
  <input type="radio" name="radio" ng-value="1" ng-change="radioSelected()" ng-model="form.radio"/>
  <input type="radio" name="radio" ng-value="2" ng-change="radioSelected()" ng-model="form.radio"/>
</div>

Upvotes: 0

Related Questions