0

I'm using Bootstrap radio button groups and am having a hard time getting the selected value into my controller. I have a small snippet of JS to set the selection on which button was clicked:

$(document).ready(function() {
    $('form .btn-group label').on('click', function() {
        $(this).find('input').prop('checked', true);
    });
});

Here is example HTML:

<form name="add-form" ng-submit="addFavorites()" novalidate>
<div class="form-group">
    <label class="control-label">Color</label>
    <div class="btn-group" data-toggle="buttons">
        <label class="btn">
            <input type="radio" name="color" value="red" class="form-control" ng-model="favorites.color" ng-required="true">Red
        </label>
       <label class="btn">
            <input type="radio" name="color" value="blue" class="form-control" ng-model="favorites.color" ng-required="true">Blue
        </label>
    </div>
</div>
</form>

Now when I submit this with ng-submit to this function, I do not get any console logged values for my radio buttons.

$scope.addFavorites = function() {
    angular.forEach($scope.favorites, function(value, key) {
        console.log(key, value);
    });
};

What am I doing wrong?

1
  • have you tried declaring $scope.favorites = {} in the controller ? Explanation: if $scope.favorites is not declared, you'll not be able to access the element "color" of an undefined element. Commented Jan 6, 2017 at 8:06

1 Answer 1

1
  1. You do not need this code:

    (document).ready(function() {
      $('form .btn-group label').on('click', function() {
        $(this).find('input').prop('checked', true);
      });
    });
    

Your radio button is wrapped with its label so HTML5 will propagate click from the label to the radio.

  1. Initialize your $scope.favorites object to {}

That is it, in submit you can get your $scope.favorites object with all its arguments.

Plunker: http://plnkr.co/edit/OatdIsvCUBSniHHQFyxG?p=preview

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.