Krish
Krish

Reputation: 4232

How to get value of selected radio button

I am trying to get selected radio button value using below code but i am getting undefined value. what is my mistake?

html

<form name="form" class="form-horizontal" role="form">

    <!-- RADIO BUTTONS -->
    <div class="form-group">
        <label class="col-sm-2 control-label">Clouds</label>
        <div class="col-sm-6">
            <label class="radio-inline" ng-repeat="option in entity.fields">
                <input type="radio" ng-model="data" name="option.name" value="{{option.id}}">
                {{option.name}}
            </label>
        </div>
    </div>

    <br />
    <button type="submit" id="submit" ng-click="save(data)">Submit</button>
    <br />

</form>

controller

routerApp.controller('DynamicController2', ['$scope', function ($scope) {
    // we would get this from the api
    $scope.entity = {
        name: "my favorite fruits",
        fields:
            [{ id: 1, name: "orange" }, { id: 2, name: "pink" }, { id: 3, name: "gray" }, { id: 4, name: "cyan" }]
    };
    $scope.save = function (data) {
        alert(data);
    }
}]);

Upvotes: 0

Views: 47

Answers (1)

Ronit Roy
Ronit Roy

Reputation: 960

The variable 'data' used in ng-modal is not defined in the controller. You need to define 'data' variable as $scope. Then there's no need to pass the variable to the function save. here how your controller should be

routerApp.controller('DynamicController2', ['$scope', function ($scope) {
// we would get this from the api
 $scope.data;
$scope.entity = {
    name: "my favorite fruits",
    fields:
        [{ id: 1, name: "orange" }, { id: 2, name: "pink" }, { id: 3, name: "gray" }, { id: 4, name: "cyan" }]
};
$scope.save = function () {
    alert($scope.data);
}

}]);

And your button in html should be like :

<button type="submit" id="submit" ng-click="save()">Submit</button>

Hopefully this will solve your problem.

Upvotes: 1

Related Questions