6

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?

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • I'm having the same question, and it is a bootstrap rendering question. The code in the answers may set the radio state, but they don't change the bootstrap visuals. I think the current answers miss the mark, not taking bootstrap into consideration. Here's a jsfiddle demonstrating the problem: https://jsfiddle.net/JonathanN/ba7d24k3/ I am endeavoring to find an answer, I will give the question a bump in the meantime. – JonathanN Feb 09 '16 at 15:40
  • Added a new question based on this one with my answer: https://stackoverflow.com/questions/35296686/is-this-the-right-way-to-set-the-radio-button-to-checked-in-bootstrap – JonathanN Feb 09 '16 at 16:08

3 Answers3

3

Since the male is a value attribute, use:

document.querySelector("input[value='male']").checked = true;

document.querySelector

Gaurang Tandon
  • 6,504
  • 11
  • 47
  • 84
0

It's easier if you change the id, correspond to each gender, so you can apply js like below:

function check() {
    document.getElementById("gender-male").checked = true;
}
function uncheck() {
    document.getElementById("gender-male").checked = false;
}

OR, if you want to set it as checked by default, then you can use HTML 5 attribute, like below:

<label class="btn btn-info">
    <input checked type="radio" id="match-three" name="options">Three numbers
</label>

Check out this question: bootstrap-set-initial-radio-button-checked-in-html

Community
  • 1
  • 1
Bla...
  • 7,228
  • 7
  • 27
  • 46
0

Html :

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

Javascript :

function check() {
    document.getElementById("male").checked = true;
}
wadge
  • 428
  • 5
  • 18
J Prakash
  • 1,323
  • 8
  • 13