Bootstrap: set initial radio button checked in HTML

社会主义新天地 提交于 2020-01-21 02:37:04

问题


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.

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.

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

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


回答1:


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

<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.

  • Having a checked attribute on the input will ensure correct state on the form field
  • Adding an active class on the label will set the correct visual state

Reference documentation.




回答2:


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

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

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




回答3:


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...

<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.



来源:https://stackoverflow.com/questions/19541484/bootstrap-set-initial-radio-button-checked-in-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!