【问题标题】:How to create checkbox inside dropdown?如何在下拉列表中创建复选框?
【发布时间】:2013-10-06 08:32:02
【问题描述】:

我想创建一个多选下拉列表。实际上,我必须使用下拉菜单选择多个选项。当我简单地这样做时,如下所示:

<select>
 <option><input type="checkbox"></option>
</select>

然后复选框显示在下拉字段的前面。但我想为每个选项而不是整体创建它,以便我可以选择多个选项。有没有办法做到这一点?

【问题讨论】:

标签: javascript html css


【解决方案1】:

这是一个简单的下拉清单:

var checkList = document.getElementById('list1');
checkList.getElementsByClassName('anchor')[0].onclick = function(evt) {
  if (checkList.classList.contains('visible'))
    checkList.classList.remove('visible');
  else
    checkList.classList.add('visible');
}
.dropdown-check-list {
  display: inline-block;
}

.dropdown-check-list .anchor {
  position: relative;
  cursor: pointer;
  display: inline-block;
  padding: 5px 50px 5px 10px;
  border: 1px solid #ccc;
}

.dropdown-check-list .anchor:after {
  position: absolute;
  content: "";
  border-left: 2px solid black;
  border-top: 2px solid black;
  padding: 5px;
  right: 10px;
  top: 20%;
  -moz-transform: rotate(-135deg);
  -ms-transform: rotate(-135deg);
  -o-transform: rotate(-135deg);
  -webkit-transform: rotate(-135deg);
  transform: rotate(-135deg);
}

.dropdown-check-list .anchor:active:after {
  right: 8px;
  top: 21%;
}

.dropdown-check-list ul.items {
  padding: 2px;
  display: none;
  margin: 0;
  border: 1px solid #ccc;
  border-top: none;
}

.dropdown-check-list ul.items li {
  list-style: none;
}

.dropdown-check-list.visible .anchor {
  color: #0094ff;
}

.dropdown-check-list.visible .items {
  display: block;
}
<div id="list1" class="dropdown-check-list" tabindex="100">
  <span class="anchor">Select Fruits</span>
  <ul class="items">
    <li><input type="checkbox" />Apple </li>
    <li><input type="checkbox" />Orange</li>
    <li><input type="checkbox" />Grapes </li>
    <li><input type="checkbox" />Berry </li>
    <li><input type="checkbox" />Mango </li>
    <li><input type="checkbox" />Banana </li>
    <li><input type="checkbox" />Tomato</li>
  </ul>
</div>

【讨论】:

  • 当用户点击外部时你能看到下拉列表吗?
  • 你想隐藏它吗?这就是你的意思ryt?如果是这样,我已经做了一些改变。在容器上放置一个 tabindex 并捕获它的模糊事件。这是使事情发挥作用的最便宜的方法之一。您只能使用 css3 来执行此操作。或者你可以在文档元素上附加一个事件监听器。
  • 这很好,但在最新版本的 chrome 中不起作用。您需要更改显示样式。见:jsfiddle.net/evfnLn0x
  • 嗨,这在 IE9 中不起作用。有没有机会让它在 IE9 中运行?
【解决方案2】:

这不能仅在 HTML 中完成(将表单元素放入 option 元素中)。

或者您可以只使用标准的select multiple 字段。

<select multiple>
  <option value="a">a</option>
  <option value="b">b</option>
  <option value="c">c</option>
</select>

【讨论】:

  • 您提供的链接已损坏
  • @NaumanAhmad 这个答案是 5 岁。欢迎提出修改建议。
【解决方案3】:

var expanded = false;

function showCheckboxes() {
  var checkboxes = document.getElementById("checkboxes");
  if (!expanded) {
    checkboxes.style.display = "block";
    expanded = true;
  } else {
    checkboxes.style.display = "none";
    expanded = false;
  }
}
.multiselect {
  width: 200px;
}

.selectBox {
  position: relative;
}

.selectBox select {
  width: 100%;
  font-weight: bold;
}

.overSelect {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}

#checkboxes {
  display: none;
  border: 1px #dadada solid;
}

#checkboxes label {
  display: block;
}

#checkboxes label:hover {
  background-color: #1e90ff;
}
<form>
  <div class="multiselect">
    <div class="selectBox" onclick="showCheckboxes()">
      <select>
        <option>Select an option</option>
      </select>
      <div class="overSelect"></div>
    </div>
    <div id="checkboxes">
      <label for="one">
        <input type="checkbox" id="one" />First checkbox</label>
      <label for="two">
        <input type="checkbox" id="two" />Second checkbox</label>
      <label for="three">
        <input type="checkbox" id="three" />Third checkbox</label>
    </div>
  </div>
</form>

【讨论】:

    【解决方案4】:

    您始终可以使用带有选择标签的 multiple 或 multiple = "true" 选项,但是有一个jquery 插件使它更漂亮。它被称为选择,可以找到here。

    This fiddle-example might help you to get started

    谢谢。

    【讨论】:

      【解决方案5】:

      我不得不提前说,Naveen的回答让我深受启发,所以我根据回答创建了自己的解决方案。

      以下 3 个函数是我们多选的基础:

      • 初始化功能 - 检测用户何时点击离开以关闭下拉菜单
      • 检测用户何时单击下拉菜单以将其展开的函数
      • 检测复选框单击事件以更新标签的函数

      一些改进包括:

      • 设计如bootstrap 5
      • 点击离开时折叠
      • 使用值列表更新标签
      • 添加了滚动条的 Y 轴溢出

      我还尝试坚持使用原生 JS(没有 jQuery)并尽可能多地使用原生 Bootstrap 5 样式

      这是视频:

      我无意制作适合每个人需求的即用型解决方案,因此请根据自己的喜好进行调整。我个人期待添加搜索功能。

      小提琴:

      window.onload = (event) => {
        initMultiselect();
      };
      
      function initMultiselect() {
        checkboxStatusChange();
      
        document.addEventListener("click", function(evt) {
          var flyoutElement = document.getElementById('myMultiselect'),
            targetElement = evt.target; // clicked element
      
          do {
            if (targetElement == flyoutElement) {
              // This is a click inside. Do nothing, just return.
              //console.log('click inside');
              return;
            }
      
            // Go up the DOM
            targetElement = targetElement.parentNode;
          } while (targetElement);
      
          // This is a click outside.
          toggleCheckboxArea(true);
          //console.log('click outside');
        });
      }
      
      function checkboxStatusChange() {
        var multiselect = document.getElementById("mySelectLabel");
        var multiselectOption = multiselect.getElementsByTagName('option')[0];
      
        var values = [];
        var checkboxes = document.getElementById("mySelectOptions");
        var checkedCheckboxes = checkboxes.querySelectorAll('input[type=checkbox]:checked');
      
        for (const item of checkedCheckboxes) {
          var checkboxValue = item.getAttribute('value');
          values.push(checkboxValue);
        }
      
        var dropdownValue = "Nothing is selected";
        if (values.length > 0) {
          dropdownValue = values.join(', ');
        }
      
        multiselectOption.innerText = dropdownValue;
      }
      
      function toggleCheckboxArea(onlyHide = false) {
        var checkboxes = document.getElementById("mySelectOptions");
        var displayValue = checkboxes.style.display;
      
        if (displayValue != "block") {
          if (onlyHide == false) {
            checkboxes.style.display = "block";
          }
        } else {
          checkboxes.style.display = "none";
        }
      }
      .multiselect {
        width: 100%;
      }
      
      .selectBox {
        position: relative;
      }
      
      .selectBox select {
        width: 100%;
      }
      
      .overSelect {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
      }
      
      #mySelectOptions {
        display: none;
        border: 0.5px #7c7c7c solid;
        background-color: #ffffff;
        max-height: 150px;
        overflow-y: scroll;
      }
      
      #mySelectOptions label {
        display: block;
        font-weight: normal;
        display: block;
        white-space: nowrap;
        min-height: 1.2em;
        background-color: #ffffff00;
        padding: 0 2.25rem 0 .75rem;
        /* padding: .375rem 2.25rem .375rem .75rem; */
      }
      
      #mySelectOptions label:hover {
        background-color: #1e90ff;
      }
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js"></script>
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
      
      <div class="container-fluid">
      
      
        <div class="form-group col-sm-8">
          <label for="dur">BS original select</label>
          <select id="dur" class="form-select">
            <option value="12" selected>One Year</option>
            <option value="24">Two Year</option>
            <option value="36">Three Year</option>
            <option value="48">Four year</option>
            <option value="60">Five Year</option>
          </select>
        </div>
      
        <div class="form-group col-sm-8">
          <label for="myMultiselect">BS custom multiselect</label>
          <div id="myMultiselect" class="multiselect">
            <div id="mySelectLabel" class="selectBox" onclick="toggleCheckboxArea()">
              <select class="form-select">
                <option>somevalue</option>
              </select>
              <div class="overSelect"></div>
            </div>
            <div id="mySelectOptions">
              <label for="one"><input type="checkbox" id="one" onchange="checkboxStatusChange()" value="one" /> First checkbox</label>
              <label for="two"><input type="checkbox" id="two" onchange="checkboxStatusChange()" value="two" /> Second checkbox</label>
              <label for="three"><input type="checkbox" id="three" onchange="checkboxStatusChange()" value="three" /> Third checkbox</label>
              <label for="four"><input type="checkbox" id="four" onchange="checkboxStatusChange()" value="four" /> Third checkbox</label>
              <label for="five"><input type="checkbox" id="five" onchange="checkboxStatusChange()" value="five" /> First checkbox</label>
              <label for="six"><input type="checkbox" id="six" onchange="checkboxStatusChange()" value="six" /> Second checkbox</label>
              <label for="seven"><input type="checkbox" id="seven" onchange="checkboxStatusChange()" value="seven" /> Third checkbox</label>
              <label for="eight"><input type="checkbox" id="eight" onchange="checkboxStatusChange()" value="eight" /> First checkbox</label>
              <label for="nine"><input type="checkbox" id="nine" onchange="checkboxStatusChange()" value="nine" /> Second checkbox</label>
              <label for="ten"><input type="checkbox" id="ten" onchange="checkboxStatusChange()" value="ten" /> Third checkbox</label>
            </div>
          </div>
        </div>
      
      </div>

      【讨论】:

      • 这对我有帮助,谢谢你的好工作
      【解决方案6】:

      使用 Bootstrap 和 JQuery 的非常简单的代码,无需任何额外的 javascript 代码:

      HTML:

      <div class="dropdown">
        <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown button
        </button>
        <form class="dropdown-menu" aria-labelledby="dropdownMenuButton">
          <label class="dropdown-item"><input type="checkbox" name="" value="one">First checkbox</label>
          <label class="dropdown-item"><input type="checkbox" name="" value="two">Second checkbox</label>
          <label class="dropdown-item"><input type="checkbox" name="" value="three">Third checkbox</label>
        </form>
      </div>
      

      CSS:

      .dropdown-menu label {
        display: block;
      }
      

      https://codepen.io/funkycram/pen/joVYBv

      【讨论】:

      • ^这是一个非常好的选择
      【解决方案7】:

      带有复选框和 jQuery 的多个下拉菜单。

      <div id="list3" class="dropdown-check-list" tabindex="100">
      <span class="anchor">Which development(s) are you interested in?</span>
        <ul class="items">
            <li><input id="answers_2529_the-lawns" name="answers[2529][answers][]" type="checkbox" value="The Lawns"/><label for="answers_2529_the-lawns">The Lawns</label></li>
            <li><input id="answers_2529_the-residence" name="answers[2529][answers][]" type="checkbox" value="The Residence"/><label for="answers_2529_the-residence">The Residence</label></li>
        </ul>
      </div>
      
      <style>
      .dropdown-check-list{
      display: inline-block;
      width: 100%;
      }
      .dropdown-check-list:focus{
      outline:0;
      }
      .dropdown-check-list .anchor {
      width: 98%;
      position: relative;
      cursor: pointer;
      display: inline-block;
      padding-top:5px;
      padding-left:5px;
      padding-bottom:5px;
      border:1px #ccc solid;
      }
      .dropdown-check-list .anchor:after {
      position: absolute;
      content: "";
      border-left: 2px solid black;
      border-top: 2px solid black;
      padding: 5px;
      right: 10px;
      top: 20%;
      -moz-transform: rotate(-135deg);
      -ms-transform: rotate(-135deg);
      -o-transform: rotate(-135deg);
      -webkit-transform: rotate(-135deg);
      transform: rotate(-135deg);
      }
      .dropdown-check-list .anchor:active:after {
      right: 8px;
      top: 21%;
      }
      .dropdown-check-list ul.items {
      padding: 2px;
      display: none;
      margin: 0;
      border: 1px solid #ccc;
      border-top: none;
      }
      .dropdown-check-list ul.items li {
      list-style: none;
      }
      .dropdown-check-list.visible .anchor {
      color: #0094ff;
      }
      .dropdown-check-list.visible .items {
      display: block;
      }
      </style>
      
      <script>
      jQuery(function ($) {
              var checkList = $('.dropdown-check-list');
              checkList.on('click', 'span.anchor', function(event){
                  var element = $(this).parent();
      
                  if ( element.hasClass('visible') )
                  {
                      element.removeClass('visible');
                  }
                  else
                  {
                      element.addClass('visible');
                  }
              });
          });
      </script>
      

      【讨论】:

        【解决方案8】:

        只需使用 bootstrap-multiselect,您就可以使用多选选项和更多功能填充下拉列表。

        有关文档和教程,您可以访问以下链接

        https://www.npmjs.com/package/bootstrap-multiselect

        http://davidstutz.de/bootstrap-multiselect/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-09-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-07-21
          • 2011-08-07
          • 2016-09-14
          相关资源
          最近更新 更多