twitter-bootstrap Bootstrap:设置在 HTML 中选中的初始单选按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19541484/
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 18:56:54  来源:igfitidea点击:

Bootstrap: set initial radio button checked in HTML

twitter-bootstraptwitter-bootstrap-3

提问by Richard

I'm using Bootstrap's JavaScript buttons to style some radio buttons, and I don't seem to be able to set an initial button as checked.

我正在使用 Bootstrap 的 JavaScript 按钮来设置一些单选按钮的样式,但我似乎无法将初始按钮设置为选中状态。

Here is my code:

这是我的代码:

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-info">
    <input checked="checked" type="radio" id="match-three" name="options">Three numbers
  </label>
  <label class="btn btn-info">
    <input type="radio" name="options" id="match-four">Four numbers
  </label>
</div>

The first button has checked="checked", but it isn't being styled as checked.

第一个按钮有checked="checked",但它的样式没有被选中。

The buttons are being styled OK after click events, so I'm not sure what is going wrong on initial load.

单击事件后按钮的样式设置为 OK,所以我不确定初始加载时出了什么问题。

Bootply version here: http://bootply.com/89566

Bootply 版本在这里:http://bootply.com/89566

采纳答案by André Dion

If you're using the HTML 5 doctype, just use checkedwithout any value:

如果您使用的是 HTML 5 文档类型,请使用checked不带任何值的:

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

checked="checked"should work as well, so you'll have to clarify what's not working for you.

checked="checked"也应该有效,所以你必须澄清什么对你不起作用。

  • Having a checkedattribute on the inputwill ensure correct state on the form field
  • Adding an activeclass on the labelwill set the correct visual state
  • 拥有一个checked属性input将确保表单字段的正确状态
  • 添加一个activelabel将设置正确的视觉状态

Reference documentation.

参考文档

回答by Zim

If you want the Bootstrap button()component to recognize the checkedinputs initially you need to add some jQuery like..

如果您希望 Bootstrapbutton()组件checked最初识别输入,您需要添加一些 jQuery,例如..

$('[checked="checked"]').parent().addClass("active");

This will set the active state to the appropriate buttons/labels in the group.

这会将活动状态设置为组中适当的按钮/标签。

回答by bbengfort

Like Skelly mentioned, the active class is what Bootstrap is toggling, it doesn't look at the checked attribute. You don't have to do it with Javascript however...

就像 Skelly 提到的那样,活动类是 Bootstrap 正在切换的,它不查看已检查的属性。但是,您不必使用 Javascript 来执行此操作...

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

Will give you what you're looking for.

会给你你正在寻找的东西。