twitter-bootstrap 如何在 Bootstrap 中将单选按钮设置为“已选中”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24463822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 21:01:44  来源:igfitidea点击:

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

javascripthtmltwitter-bootstrap

提问by TIMEX

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

我使用 Bootstrap 按钮作为单选按钮。 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?

如何使用 JavaScript 将“男性”设置为检查?

回答by Gaurang Tandon

Since the maleis a valueattribute, use:

由于male是一个value属性,请使用:

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

document.querySelector

document.querySelector

回答by Bla...

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

如果你改变id,对应每个性别就更容易了,所以你可以像下面这样应用js:

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:

或者,如果要将其设置为默认选中,则可以使用 HTML 5 属性,如下所示:

<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

看看这个问题:bootstrap-set-initial-radio-button-checked-in-html

回答by J Prakash

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 :

Javascript :

function check() {
    document.getElementById("male").checked = true;
}