Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the right way to set the radio button to “checked” in Bootstrap?

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?

like image 991
JonathanN Avatar asked Nov 15 '25 19:11

JonathanN


2 Answers

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.

like image 123
Kaleb Anderson Avatar answered Nov 18 '25 08:11

Kaleb Anderson


Figured out a bootstrap way to do it.

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

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

like image 40
JonathanN Avatar answered Nov 18 '25 07:11

JonathanN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!