5

我想在 Bootstrap 3.0.2 中检查组复选框的状态。文档

html:

<div class="btn-group" data-toggle="buttons">
        <label class="btn btn-default">
        <input type="checkbox" name="123" data-toggle="button"> <span class="glyphicon glyphicon-star"></span> 123
      </label>
      <label class="btn btn-default">
        <input type="checkbox" name="456"> <span class="glyphicon glyphicon-star-empty"></span> 456
      </label>
    </div>

data-toggle="button"不起作用。jsfiddle

如何解决?谢谢。

4

3 回答 3

11

To actually check the input, you will need to add the checked property. This will not actually make it appear checked, but is important if you are using this in a form and actually want the input to be checked by default.

<input type="checkbox" name="123" data-toggle="button" checked>

To make it look checked (or pressed), add class .active to the .btn label wrapping it.

 <label class="btn btn-default active">

http://jsfiddle.net/ZktYG/2/

Not sure why data-toggle="buttons" isn't working. Could be related to this: https://github.com/twbs/bootstrap/issues/8816

For now, you can achieve the same effect through JS by doing something like:

$('.btn-group').on('input', 'change', function(){
   var checkbox = $(this);
   var label = checkbox.parent('label');
   if (checkbox.is(':checked'))  {
      label.addClass('active');
   }
   else {
      label.removeClass('active');
   }
});
于 2013-11-10T15:22:59.120 回答
2

已经好几年了;但是,我想解决上面为什么 data-toggle="button" 不起作用的实际问题。

答案是删除 <input> 上的 data-toggle="button"。

<div class="btn-group" data-toggle="buttons">
    <label class="btn btn-default">
        <input type="checkbox" name="123"> 123
    </label>
    <label class="btn btn-default">
        <input type="checkbox" name="456"> 456
    </label>
</div>
于 2016-06-22T23:53:42.663 回答
0

我通过创建一个自定义属性来解决这个问题,该属性包含它是否处于活动状态,然后在 JQuery 的单击事件中设置该值。

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active check_button" id="check1">
    <input type="checkbox" autocomplete="off" checked data-checked=true> Checkbox 1 (pre-checked)
  </label>
  <label class="btn btn-primary check_button" id="check2">
    <input type="checkbox" autocomplete="off" data-checked=false> Checkbox 2
  </label>
  <label class="btn btn-primary check_button" id="check3">
    <input type="checkbox" autocomplete="off" data-checked=false> Checkbox 3
  </label>
</div>

您可以在小提琴中看到一个工作示例, https://jsfiddle.net/jeffbeagley/DTcHh/34024/

于 2017-06-20T15:20:55.850 回答