3

I am repurposing TIMEX's question that's been marked as duplicate, because I believe it is not a duplicate and I hit the same issue.

How do I set the radio button to "checked" in Bootstrap?

I'm using Bootstrap buttons as a radio button. http://getbootstrap.com/javascript/#buttons

This is my current code:

<div  class="btn-group col-md-2" data-toggle="buttons">
    <label class="btn btn-gender btn-default active">
        <input type="radio" id="gender" name="gender" value="female"> Girls
    </label>
    <label class="btn btn-gender btn-default">
        <input type="radio" id="gender" name="gender" value="male"> Guys
    </label> 
</div> 

How can I set "male" to checked using JavaScript?

Here's my reproduction of the problem: https://jsfiddle.net/JonathanN/ba7d24k3/

I couldn't find a solution in the getbootstrap.com documentation or readily on stackoverflow, so here's what I came up with: https://jsfiddle.net/JonathanN/ba7d24k3/2/

var toggleRadioButton = function ($parent, name, value) {
  var $allButtons = $parent.find('input[name="' + name + '"]');
  $allButtons.prop('checked', false);
  $allButtons.parents('label.btn').removeClass('active');
  var $targetButton = $parent.find('input[name="' + name + '"][value="' + value + '"]');
  $targetButton.prop('checked', true);
  $targetButton.parents('label.btn').addClass('active');
};

I used jQuery, but it could be coded up in more verbose javascript as well. Hopefully I've established that is not a duplicate of the basic how to set a radio button with javascript question.

My question: Is there an easier way?

JonathanN
  • 672
  • 7
  • 17

2 Answers2

1

What if you do something like

$parent.find('input[name="' + name + '"][value="' + value + '"]').click();

to trigger a click event for whichever radio option you want selected? This way bootstrap can handle all the CSS class changes and such.

1

Figured out a bootstrap way to do it.

$('#genderM').parents('.btn').button('toggle');

https://jsfiddle.net/JonathanN/ba7d24k3/5/

JonathanN
  • 672
  • 7
  • 17