Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 709
user2057574 Avatar asked Mar 01 '13 20:03

user2057574


1 Answers

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

like image 80
Ben Lesh Avatar answered Sep 28 '22 01:09

Ben Lesh