Bootstrap下拉菜单中的复选框允许多个复选框而不是一个

Bootstrap drop down with check box(s) allowing for multiple check boxes instead of just one

本文关键字:复选框 一个 下拉菜单 许多个 Bootstrap      更新时间:2023-09-26

我有一个Bootstrap下拉菜单,允许用户在下拉列表中的项目旁边添加复选框。但是,用户可以添加多个复选框——所需的行为是用户只能选择一个复选框。如果用户选择了一个复选框,则应删除另一个复选复选框。

$("document").ready(function() {
  $('.dropdown-menu').on('click', function(e) {
    if($('.checkbox').count() > 1){
           if($(this).hasClass('dropdown-menu-form')) {
          e.stopPropagation();
      }
    }
  });
});
.dropdown-menu-form {
  padding: 5px 10px 0;
  max-height: 100px;
  overflow-y: scroll;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="dropdown">
  <a class="dropdown-toggle btn" data-toggle="dropdown" href="#">
       Toggle dropdown
      <b class="caret"></b>
   </a>
  <ul class="dropdown-menu dropdown-menu-form" role="menu">
    <li>
      <label class="checkbox">
        <input type="checkbox">Checkbox 1
      </label>
    </li>
    <li>
      <label class="checkbox">
        <input type="checkbox">Checkbox 2
      </label>
    </li>
    <li>
      <label class="checkbox">
        <input type="checkbox">Checkbox 2
      </label>
    </li>
    <li>
      <label class="checkbox">
        <input type="checkbox">Checkbox 2
      </label>
    </li>
    <li>
      <label class="checkbox">
        <input type="checkbox">Checkbox 2
      </label>
    </li>
    <li>
      <label class="checkbox">
        <input type="checkbox">Checkbox 3
      </label>
    </li>
  </ul>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

我试图用.checkbox的klass数来实现一些东西,但没有成功。我只是希望有行为,如果用户点击复选框,上一个复选框将被删除。

创建复选框是为了允许多次检查,可以将其视为you can have this, that, and that。你正在找一个单选按钮。单选按钮被视为you get thisyou get that

试试这个

<li>
        <label class="radio-btn">
            <input type="radio">
            Radio 1
        </label>
    </li>

JS

$("document").ready(function() {
  $('.dropdown-menu').on('click', function(e) {
    if($('.radio-btn').count() > 1){
           if($(this).hasClass('dropdown-menu-form')) {
          e.stopPropagation();
      }
    }
  });
});