【问题标题】:bootstrap button group select any two checkbox from many引导按钮组从许多中选择任意两个复选框
【发布时间】:2016-04-09 21:33:39
【问题描述】:

我必须从 4-5 个复选框中选择任意 2 个复选框。为了制作复选框,我正在使用引导程序。

下面是我的代码

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="checkbox" autocomplete="off" checked> Checkbox 1 (pre-checked)
  </label>
  <label class="btn btn-primary">
    <input type="checkbox" autocomplete="off"> Checkbox 2
  </label>
  <label class="btn btn-primary">
    <input type="checkbox" autocomplete="off"> Checkbox 3
  </label>
  <label class="btn btn-primary">
    <input type="checkbox" autocomplete="off"> Checkbox 4
  </label>
</div>

但我希望最多可以选择 2 个复选框。其他需要禁用

我为此使用http://getbootstrap.com/javascript/#buttons-checkbox-radio,当我点击特定标签而不是禁用其他标签并点击事件时

【问题讨论】:

    标签: jquery twitter-bootstrap checkbox twitter-bootstrap-3


    【解决方案1】:

    先添加一个类&lt;input type="checkbox" class="ch" autocomplete="off"&gt;
    使用 `.change() 事件处理程序来触发选中/取消选中复选框的代码。

    $('.ch').change(function() {
          $($('.btn-group').find("input[type='checkbox']")).each(function() {
            $(this).attr("disabled", false);
          });
          var check = $($('.btn-group').find("input[type='checkbox']:checked")).length;
          if (check > 1) {
            $('.btn-group').find("input[type='checkbox']").not(":checked").attr("disabled", true);
          }
        });
    

    这是 jsFiddle 中的一个示例:https://jsfiddle.net/jagrati16/q8jo77c2/

    【讨论】:

      【解决方案2】:

      你可以看下面的代码来做你想做的事。

      $('input[type="checkbox"]').change(function() {
        var number = $('.btn-group').find("input[type='checkbox']:checked").length;
        if (number > 1) {
          $('.btn-group').find("input[type='checkbox']").not(":checked").attr("disabled", true);
        }else {
          $('.btn-group').find("input[type='checkbox']").attr("disabled", false);
        }
      });
      

      我也创建了一个jsfiddle。我希望这能解决您的问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-26
        • 2014-10-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多