How can I get the value of the checked radio button when submitting a form using angularjs? - angularjs

I have a few forms. Each form have a few possible radio buttons and a submit button. Only one radio button can be checked (using the same name attribute for each radio). How can I get the checked radio button's value when the form is submitted, using angularjs? #blesh advised to use the same ng-model for each input, but note that the problem is that the input tags are generated using ng-repeat, and this is where the problem starts. I need, of course, naturally, only one button for a bunch of inputs. It is well described in the following plunker, after playing with #blesh 's Answer: http://plnkr.co/edit/5KTQRGdPv3dbP462vq1a?p=preview In it, you can see that the alert shows the initial value and not the current selected input.

Your radio button's value will be available on whatever scope property you've assigned ng-model="" to on the input element. Try something like this:
JS
app.controller('MyCtrl', function($scope){
$scope.submitForm = function (){
alert($scope.radioValue):
};
$scope.radioValue = 1;
});
HTML
<form name="myForm" ng-controller="MyCtrl" ng-submit="submitForm()">
<label><input type="radio" name="test" ng-model="radioValue" value="1"/> One</label>
<label><input type="radio" name="test" ng-model="radioValue" value="2"/> Two</label>
<label><input type="radio" name="test" ng-model="radioValue" value="3"/> Three</label>
<div>currently selected: {{radioValue}}</div>
<button type="submit">Submit</button>
</form>
And, so you can see it working, here is a plunker demonstrating the example

just add $parent in ng-model .
<form name="myForm" ng-submit="submitForm()">
<label data-ng-repeat="i in [1,2,3]"><input type="radio" name="test" ng-model="$parent.radioValue" value="{{i}}"/>{{i}}</label>
<div>currently selected: {{radioValue}}</div>
<button type="submit">Submit</button>
</form>

Combination with ng-value
app.controller('MyCtrl', function($scope){
$scope.submitForm = function() {
*****
};
$scope.radioBtn = {
name: 'radioButton'
};
$scope.radioValueOne = {"id": "1", "value": "whatever you want"};
$scope.radioValueTwo = {"id": "2", "value": "whatever you want"};
$scope.radioValueThree = {"id": "3", "value": "whatever you want"};
});
<form name="myForm" ng-controller="MyCtrl" ng-submit="submitForm()">
<label><input type="radio" name="test" ng-model="radioBtn.name" ng-value="radioValueOne"/> One</label>
<label><input type="radio" name="test" ng-model="radioBtn.name" ng-value="radioValueTwo"/> Two</label>
<label><input type="radio" name="test" ng-model="radioBtn.name" ng-value="radioValueThree"/> Three</label>
<div>currently selected: {{radioBtn.name}}</div>
<button type="submit">Submit</button>
</form>

I faced this problem and found a really simple and clean solution. Here's what you should do.
In your controller, make an empty object with any name("radioValue" in this case).
In your HTML file, use same 'ng-model' for each radio button/input with same name as that of object joining 'name' attribute of each radio button(that too should be same for each button) separated by a period(.) as shown in code snippet.
The Controller
var radioValue={};
...
...
console.log($scope.radiovalue) //use JSON.strinigify if naccessary
The HTML File
<input type="radio" name="somename" ng-model="radioValue.somename" value="1"/>
<input type="radio" name="somename" ng-model="radioValue.somename" value="2"/>
<input type="radio" name="somename" ng-model="radioValue.somename" value="3"/>
//Don't forget to mention value attribute. ng-model does the work by identifying the radio-buttons/inputs by value attribute
The Output you should expect
{"somename":"1"} //if radio-button with value "1" is selected.

Related

Set value of the radio group model inside ngChange handler

I have a simple form with 3 radio button with same name="myNumber" and a method to handle ng-change event
<form name="myForm" ng-controller="ExampleController">
<label>
<input type="radio" ng-model="number" name="myNumber" value="1" ng-change="handleChange()" /> 1
</label>
<label>
<input type="radio" ng-model="number" name="myNumber" value="2" ng-change="handleChange()" /> 2
</label>
<label>
<input type="radio" ng-model="number" name="myNumber" value="3" ng-change="handleChange()" /> 3
</label>
</form>
In the change handler, I simply set the value of $scope.model to "3"
angular.module('radioExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.number = "1"; // initial value
$scope.handleChange = function() {
$scope.number = "3"; // what I want to do
};
}]);
Then I try clicking around the radio buttons to trigger the $scope.handleChange event to see if it work but since the 2nd click ahead, the result is like this:
Expected: The radio button number 3 keeps being checked.
Actual: All radio buttons are not checked at all.
Edit 1: Update fiddle example
I added this <div> as a simple log to the screen, the result of $scope.number always = "3" which is expected. What's wrong is the checked status of radio buttons
<div>
$scope.number = {{number}}
</div>
Fiddle link: http://jsfiddle.net/ujem8ndx/2/
I don't know the reason but when I remove the name attribute from the inputs, the problem's solved.
I posted this as an answer because it solved my problem but the why question is not answered.

ng-disabled not working for radio buttons and checkboxes

I am working on an AngularJS application. I am trying to create a page that allows the user to select one of three radio buttons. Two of the three also have checkboxes underneath them to allow the user to select additional options if they've selected the appropriate radio button. To try to prevent improper checkbox selections, I'm trying to set the ng-disabled attribute on the checkboxes. So far, it's not working, and I've tried several different iterations.
This is my HTML:
<div class="panel-body">
<input type="radio" id="notFraudulent" name="actionSelector" ng-model="cleared" /><label for="notFraudulentRadio"> Not Fraudulent</label><br />
<input type="checkbox" id="highVolumeCustomer" ng-model="highVolumeCustomer" ng-disabled="(fraudulent||cleared)" /><label for="highVolumeCustomer"> High Volume Customer</label><br />
<br/>
<input type="radio" id="appearsFraudulent" name="actionSelector" ng-model="fraudulent" /><label for="isFraudulentRadio"> Appears Fraudulent</label><br />
<input type="checkbox" id="reportAccount" ng-model="reportAccount" ng-disabled="(cleared||reviewed)" /><label for="reportAccount"> Report Account</label><br />
<br/>
<input type="radio" id="markReviewed" name="actionSelector" ng-model="reviewed" /><label for="markReviewed"> Mark As Reviewed For Later</label>
</div>
I have tried changing the operator on the ng-disabled expressions to &&, as I've seen some articles where it's suggested that the operators don't mean what one thinks they mean. But that doesn't work, and neither does it work if I put just a single condition in the expression. There isn't anything in the controller (yet) that tries to use or manipulate any of the ng-models in the HTML. I've come to the conclusion that there's something I'm missing with regard to the radio buttons, but I can't for the life of me figure out what.
Can anyone see what my mistake is?
you should use value property to bind special value for radio button, and when radiobutton's status is changed, the value will be kept at ng-model.
refer the code snippet below:
angular.module("app", [])
.controller("myCtrl", function($scope) {
$scope.selectedValue = 'cleared';
$scope.cleared = false;
$scope.fraudulent = false;
$scope.reviewed = false;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="panel-body" ng-app='app' ng-controller="myCtrl">
<input type="radio" id="notFraudulentRadio" name="actionSelector" value="cleared" ng-model="selectedValue" /><label for="notFraudulentRadio"> Not Fraudulent</label><br />
<input type="checkbox" id="highVolumeCustomer" ng-model="highVolumeCustomer" ng-disabled="selectedValue === 'fraudulent' || selectedValue === 'cleared'" /><label for="highVolumeCustomer"> High Volume Customer</label><br />
<br/>
<input type="radio" id="isFraudulentRadio" name="actionSelector" value="fraudulent" ng-model="selectedValue"/><label for="isFraudulentRadio"> Appears Fraudulent</label><br />
<input type="checkbox" id="reportAccount" ng-model="reportAccount" ng-disabled="selectedValue === 'cleared' || selectedValue === 'reviewed'" /><label for="reportAccount"> Report Account</label><br />
<br/>
<input type="radio" id="markReviewed" name="actionSelector" value="reviewed" ng-model="selectedValue"/><label for="markReviewed"> Mark As Reviewed For Later</label>
<br>
cleared:{{cleared}}<br>
fraudulent:{{fraudulent}}<br>
reviewed:{{reviewed}}<br>
selectedValue: {{selectedValue}}
</div>

On change radio button to no the span should hide in angular

In angular if i change my radio button from no to yes the span content should Hide.
I don't know how to take the event.
Here the fiddle
http://jsfiddle.net/Lzgqnkx9/
<div class="onoffswitch-green1">
<input type="radio" id="radios3" name="radiosgg" class="SwitchOn" value="true" checked
ng-click="radioChecked()">
<label for="radios3">Yes</label>
<input type="radio" id="radios4" name="radiosgg" class="SwitchOff" value="false" ng-
click="radiounChecked()">
<label for="radios4">No</label>
</div>
<span class="temsize">
<label>Team Size</label>
<input type="text" class="s-txtboxes">
</span>
your ans will be very helpfull .
Thanks
updated jsFiddle
Angular has an already defined behavior for handling radio inputs. You don't have to use any radioChecked function, just use combination of ng-model and value on your inputs :
<input type="radio"
ng-model="hasTeam"
value="true"/> - Yes
<input type="radio"
ng-model="hasTeam"
value="false"/> - No
<span ng-if="hasTeam">
I'm showing only if yes is selected.
</span>
Maybe you should read the docs here.
you must use ng-hide or ng-show directive
for example
HTML
<input type="radio" id="radios3" name="radiosgg" class="SwitchOn" value="true" checked
ng-click="radioChecked()" ng-model="myvar" ng-hide="hideVar">
JavaScript
$Scope.hideVar = false;
$Scope.myvar = false;
$Scope.radioChecked= function () {
$Scope.hideVar = true; // Hide your checkbox
... dosomething...
}

Radio Buttons ng-checked with ng-model

In my HTML page, I have two sets of Boolean based radio buttons: Labeled: "Yes" and "No" / Values: True and False respectively. I'm populating a full form from a PostgreSQL database table to allow the authenticated user to view the form with populated data and edit the populated fields including the radio buttons, then save the form which will save the data to the DB. All of the other text fields populate without issue; it's both collection of radio buttons I am having an issue with pre-checkmarking the radio buttons.
The below does not pre-populate the checked on front end (but adds the correct attribute of checked in HTML source):
<input id="billing-no" type="radio" name="billing" ng-model="person.billing" value="FALSE" ng-checked="person.billing == 'false'" />
<input id="billing-yes" type="radio" name="billing" ng-model="person.billing" value="TRUE" ng-checked="person.billing == 'true'" />
However, this does check the correct radio button on load:
<input id="billing-no" type="radio" name="billing" value="FALSE" ng-checked="person.billing == 'false'" />
<input id="billing-yes" type="radio" name="billing" value="TRUE" ng-checked="person.billing == 'true'" />
Note: I needed to check against the string boolean value in the directive ng-checked since the boolean value always comes back as a string from PostgreSQL. This, apparently, was a part of PostgreSQL's design when querying data from columns that have boolean data types.
When adding the ng-model directive, the radio button no longer is checked (at least in the rendered browser view). The odd part is that I looked at the source and it clearly checks the correct one. What's even more odd, is that I have to click on the radio button twice to 'check' it. I've tested this in latest version of Chrome, FF, and IE and it all results in the same issue.
The question is: when adding the ng-model directive, why would the HTML source add 'checked' in the radio button attribute, but seemingly does not mark the radio button? Furthermore, why would I have to click twice on the radio button that IS supposed to be checked?
Solution:
To fix this, I removed the ng-checked directive from the radio buttons and only used ng-model as suggested by #Cypher and #aet. I then replaced the attribute value with the directive ng-value "true" & "false". After, I set the values in the controller.
HTML
<input id="billing-no" type="radio" name="billing" ng-model="person.billing" ng-value="false" />
<input id="billing-yes" type="radio" name="billing" ng-model="person.billing" ng-value="true" />
Angular JS
app.controller('peopleCtrl', function($scope, peopleFactory){
...
peopleFactory.getPerson(personParams).then(function(data){
$scope.person = data;
/* moved from ng-checked */
$scope.person.billing = data.billing == 'true';
});
...
};
I think you should only use ng-model and should work well for you, here is the link to the official documentation of angular https://docs.angularjs.org/api/ng/input/input%5Bradio%5D
The code from the example should not be difficult to adapt to your specific situation:
<script>
function Ctrl($scope) {
$scope.color = 'blue';
$scope.specialValue = {
"id": "12345",
"value": "green"
};
}
</script>
<form name="myForm" ng-controller="Ctrl">
<input type="radio" ng-model="color" value="red"> Red <br/>
<input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
<input type="radio" ng-model="color" value="blue"> Blue <br/>
<tt>color = {{color | json}}</tt><br/>
</form>
I solved my problem simply using ng-init for default selection instead of ng-checked
<div ng-init="person.billing=FALSE"></div>
<input id="billing-no" type="radio" name="billing" ng-model="person.billing" ng-value="FALSE" />
<input id="billing-yes" type="radio" name="billing" ng-model="person.billing" ng-value="TRUE" />
[Personal Option]
Avoiding using $scope, based on John Papa Angular Style Guide
so my idea is take advantage of the current model:
(function(){
'use strict';
var app = angular.module('way', [])
app.controller('Decision', Decision);
Decision.$inject = [];
function Decision(){
var vm = this;
vm.checkItOut = _register;
function _register(newOption){
console.log('should I stay or should I go');
console.log(newOption);
}
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div ng-app="way">
<div ng-controller="Decision as vm">
<form name="myCheckboxTest" ng-submit="vm.checkItOut(decision)">
<label class="radio-inline">
<input type="radio" name="option" ng-model="decision.myWay"
ng-value="false" ng-checked="!decision.myWay"> Should I stay?
</label>
<label class="radio-inline">
<input type="radio" name="option" ng-value="true"
ng-model="decision.myWay" > Should I go?
</label>
</form>
</div>
</div>
I hope I could help ;)
Please explain why same ng-model is used? And what value is passed through ng- model and how it is passed? To be more specific, if I use console.log(color) what would be the output?

AngularJS radio buttons not marked $dirty until last button selected

I created this simple example: http://jsfiddle.net/5Bh59/.
If you switch between AngularJS 1.2.1 and 1.1.1, you'll see the radio buttons don't work properly in either version. If you watch the radio button's $dirty field, 1) for version 1.1.1, it will only be set when the first button is clicked, and 2) for version 1.2.1, it will only be set when the last button is clicked.
I read this answer: AngularJS Radio group not setting $dirty on field but I don't really understand the answer. Not only that but the fiddler example demonstrates the same behavior.
So, is this a bug in AngularJS and how can I work around it?
You either need to give each radio button input a different name, or you need to wrap each radio button in an ng-form (each of which have a different name). If you use two inputs with the same name in the same form, only the last one will be bound to the property on the FormController. If you use different names, then each input will have its own property on the FormController.
Example with different names for each radio button:
http://jsfiddle.net/BEU3V/
<form name="form" novalidate>
<input type="radio"
name="myRadio1"
ng-model="myRadio"
ng-click=""
value="Rejected"
required>Rejected<br />
<input type="radio"
name="myRadio2"
ng-model="myRadio"
ng-click=""
value="Approved"
required>Approved<br />
Form $dirty: {{form.$dirty}}<br />
Field1 $dirty: {{form.myRadio1.$dirty}}<br />
Field1 $dirty: {{form.myRadio2.$dirty}}<br />
Value: {{myRadio}}
</form>
Example wrapping with ng-form:
http://jsfiddle.net/39Rrm/1/
<form name="form" novalidate>
<ng-form name="form1">
<input type="radio"
name="myRadio"
ng-model="myRadio"
ng-click=""
value="Rejected"
required>Rejected<br />
</ng-form>
<ng-form name="form2">
<input type="radio"
name="myRadio"
ng-model="myRadio"
ng-click=""
value="Approved"
required>Approved<br />
</ng-form>
Form $dirty: {{form.$dirty}}<br />
Field1 $dirty: {{form.form1.myRadio.$dirty}}<br />
Field2 $dirty: {{form.form2.myRadio.$dirty}}<br />
Value: {{myRadio}}
</form>
If you'd like a single check for the radio group, you can wrap all the radio buttons in their own ng-form and call it something like name="radioGroup".
http://jsfiddle.net/6VVBL/
<form name="form" novalidate>
<ng-form name="radioGroup">
<input type="radio"
name="myRadio1"
ng-model="myRadio"
ng-click=""
value="Rejected"
required>Rejected<br />
<input type="radio"
name="myRadio2"
ng-model="myRadio"
ng-click=""
value="Approved"
required>Approved<br />
</ng-form>
Form $dirty: {{form.$dirty}}<br />
Group $valid: {{form.radioGroup.$valid}}<br />
Group $dirty: {{form.radioGroup.$dirty}}<br />
Value: {{myRadio}}
</form>
This answer is related but perhaps not exactly applicable, but after finding and reading this item I felt it valuable to provide, and I don't have enough points to just comment on an answer (which I thought would have been a more appropriate way to respond).
My issue was that I wanted to show a required error (using ng-messages) but when you tabbed through / past the radio button group $touched didn't turn true unless you shift-tabbed back from the next UI element back to the last radio button of the group. (When my form renders the radio buttons are not set - I'm wanting the user to make a selection and not rely on the user accepting a default.)
Here's my code:
<div class="form-group" ng-class="{'has-error': pet.genderId.$invalid && pet.genderId.$touched}">
<label class="control-label">
What is your pet's gender?
<span ng-messages="pet.genderId.$error" ng-show="pet.genderId.$invalid && pet.genderId.$touched">
<span ng-message="required">(required)</span>
</span>
</label>
<div>
<label class="radio-inline"><input type="radio" ng-model="genderId" name="genderId" value="1" required ng-blur="pet.genderId.$setTouched();" />Male</label>
<label class="radio-inline"><input type="radio" ng-model="genderId" name="genderId" value="2" required ng-blur="pet.genderId.$setTouched();" />Female</label>
<label class="radio-inline"><input type="radio" ng-model="genderId" name="genderId" value="3" required ng-blur="pet.genderId.$setTouched();" />Not sure</label>
</div>
</div>
The 'magic' was adding the ng-blur attribute to set 'touched' myself even if only the first radio button was tabbed past.
You may be able to employ a similar tactic for $dirty by calling $setDirty() in the ng-changed attribute.

Resources