127

客户给了我一个设计,它有一个选择选项菜单,其中包含一个复选框以及项目名称作为列表中的单个项目。是否有可能在“选择选项”菜单中添加一个复选框?

注意:开发者需要添加自己的 id 才能使菜单生效,如果可能的话,我只需要 HTML CSS 代码。

4

12 回答 12

222

您不能将复选框放置在选择元素内,但您可以使用 HTML、CSS 和 JavaScript 获得相同的功能。这是一个可能的工作解决方案。解释如下。

在此处输入图像描述


代码:

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>

解释:

首先,我们创建一个显示文本“选择一个选项”的选择元素,以及覆盖(重叠)选择元素 ( <div class="overSelect">) 的空元素。我们不希望用户点击选择元素——它会显示一个空选项。为了将元素与其他元素重叠,我们使用 CSS 位置属性,其值为 relative | 绝对。

为了添加功能,我们指定了一个 JavaScript 函数,当用户单击包含我们的选择元素 ( <div class="selectBox" onclick="showCheckboxes()">) 的 div 时调用该函数。

我们还创建包含复选框的 div 并使用 CSS 设置样式。上面提到的 JavaScript 函数只是将<div id="checkboxes">CSS display 属性的值从“none”更改为“block”,反之亦然。

该解决方案在以下浏览器中进行了测试:Internet Explorer 10、Firefox 34、Chrome 39。浏览器需要启用 JavaScript。


更多信息:

CSS定位

如何将一个div覆盖在另一个div上

http://www.w3schools.com/css/css_positioning.asp

CSS 显示属性

http://www.w3schools.com/cssref/pr_class_display.asp

于 2014-12-18T12:50:24.520 回答
67

迄今为止最好的插件是Bootstrap Multiselect

编辑:我很久以前写过这个。我不再推荐使用 jQuery。你应该学习一个响应式框架,比如 Vue.js、React 或 Angular,你有很多模块可供选择。我相信你会找到你需要的。例如,我通过快速谷歌搜索找到了这个。

<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<title>jQuery Multi Select Dropdown with Checkboxes</title>

<link rel="stylesheet" href="css/bootstrap-3.1.1.min.css" type="text/css" />
<link rel="stylesheet" href="css/bootstrap-multiselect.css" type="text/css" />

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/bootstrap-3.1.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap-multiselect.js"></script>

</head>

<body>

<form id="form1">

<div style="padding:20px">

<select id="chkveg" multiple="multiple">
    
    <option value="cheese">Cheese</option>
    <option value="tomatoes">Tomatoes</option>
    <option value="mozarella">Mozzarella</option>
    <option value="mushrooms">Mushrooms</option>
    <option value="pepperoni">Pepperoni</option>
    <option value="onions">Onions</option>

</select>

<br /><br />

<input type="button" id="btnget" value="Get Selected Values" />

<script type="text/javascript">

$(function() {
    
    $('#chkveg').multiselect({
        
        includeSelectAllOption: true
    });
    
    $('#btnget').click(function(){
        
        alert($('#chkveg').val());
    });
});

</script>

</div>

</form>

</body>
</html>

这是一个演示:

$(function() {

  $('#chkveg').multiselect({
    includeSelectAllOption: true
  });

  $('#btnget').click(function() {
    alert($('#chkveg').val());
  });
});
.multiselect-container>li>a>label {
  padding: 4px 20px 3px 20px;
}
<link href="https://unpkg.com/bootstrap@3.3.2/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://unpkg.com/jquery@3.3.1/dist/jquery.min.js"></script>
<script src="https://unpkg.com/bootstrap@3.3.2/dist/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/bootstrap-multiselect@0.9.13/dist/js/bootstrap-multiselect.js"></script>
<link href="https://unpkg.com/bootstrap-multiselect@0.9.13/dist/css/bootstrap-multiselect.css" rel="stylesheet"/>

<form id="form1">
  <div style="padding:20px">

    <select id="chkveg" multiple="multiple">
      <option value="cheese">Cheese</option>
      <option value="tomatoes">Tomatoes</option>
      <option value="mozarella">Mozzarella</option>
      <option value="mushrooms">Mushrooms</option>
      <option value="pepperoni">Pepperoni</option>
      <option value="onions">Onions</option>
    </select>
    
    <br /><br />

    <input type="button" id="btnget" value="Get Selected Values" />
  </div>
</form>

于 2014-08-20T21:42:48.017 回答
23

对于纯 CSS方法,您可以将:checked选择器与选择器结合使用::before来内联条件内容。

只需将类添加select-checkbox到您的select元素并包含以下 CSS:

.select-checkbox option::before {
  content: "\2610";
  width: 1.3em;
  text-align: center;
  display: inline-block;
}
.select-checkbox option:checked::before {
  content: "\2611";
}

您可以使用普通的旧 unicode 字符(带有转义的十六进制编码),如下所示:

或者如果你想增加趣味,你可以使用这些FontAwesome字形

截屏

jsFiddle和 Stack Snippets中的演示

select {
  width: 150px;
}

.select-checkbox option::before {
  content: "\2610";
  width: 1.3em;
  text-align: center;
  display: inline-block;
}
.select-checkbox option:checked::before {
  content: "\2611";
}

.select-checkbox-fa option::before {
  font-family: FontAwesome;
  content: "\f096";
  width: 1.3em;
  display: inline-block;
  margin-left: 2px;
}
.select-checkbox-fa option:checked::before {
  content: "\f046";
}
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">

<h3>Unicode</h3>
<select multiple="" class="form-control select-checkbox" size="5">
  <option>Dog</option>
  <option>Cat</option>
  <option>Hippo</option>
  <option>Dinosaur</option>
  <option>Another Dog</option>
</select>

<h3>Font Awesome</h3>
<select multiple="" class="form-control select-checkbox-fa" size="5">
  <option>Dog</option>
  <option>Cat</option>
  <option>Hippo</option>
  <option>Dinosaur</option>
  <option>Another Dog</option>
</select>

注意但请注意 IE 兼容性问题

于 2018-02-13T21:34:20.870 回答
17

尝试多项选择,尤其是多项。看起来很干净和管理的解决方案,有大量的例子。您还可以查看源代码。

<div>
  <div class="form-group row">
    <label class="col-sm-2">
      Basic Select
    </label>

    <div class="col-sm-10">
      <select multiple="multiple">
        <option value="1">1</option>
        <option value="2">2</option>
      </select>
    </div>
  </div>

  <div class="form-group row">
    <label class="col-sm-2">
      Group Select
    </label>

    <div class="col-sm-10">
      <select multiple="multiple">
        <optgroup label="Group 1">
          <option value="1">1</option>
          <option value="2">2</option>
        </optgroup>
        <optgroup label="Group 2">
          <option value="6">6</option>
          <option value="7">7</option>
        </optgroup>
        <optgroup label="Group 3">
          <option value="11">11</option>
          <option value="12">12</option>
        </optgroup>
      </select>
    </div>
  </div>
</div>

<script>
  $(function() {
    $('select').multipleSelect({
      multiple: true,
      multipleWidth: 60
    })
  })
</script>
于 2015-04-11T01:55:48.200 回答
10

替代 Vanilla JS 版本,点击外部隐藏复选框:

let expanded = false;
const multiSelect = document.querySelector('.multiselect');

multiSelect.addEventListener('click', function(e) {
  const checkboxes = document.getElementById("checkboxes");
    if (!expanded) {
    checkboxes.style.display = "block";
    expanded = true;
  } else {
    checkboxes.style.display = "none";
    expanded = false;
  }
  e.stopPropagation();
}, true)

document.addEventListener('click', function(e){
  if (expanded) {
    checkboxes.style.display = "none";
    expanded = false;
  }
}, false)

我正在使用 addEventListener 而不是 onClick,以便利用捕获/冒泡阶段选项以及 stopPropagation()。您可以在此处阅读有关捕获/冒泡的更多信息:https ://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

其余代码与 vitfo 的原始答案匹配(但在 html 中不需要 onclick())。有几个人要求这个功能没有 jQuery。

这是代码笔示例https://codepen.io/davidysoards/pen/QXYYYa?editors=1010

于 2019-07-11T12:21:26.667 回答
9

我从@vitfo 答案开始,但我想在<option>里面<select>而不是复选框输入,所以我把所有答案放在一起来做这个,有我的代码,我希望它会对某人有所帮助。

$(".multiple_select").mousedown(function(e) {
    if (e.target.tagName == "OPTION") 
    {
      return; //don't close dropdown if i select option
    }
    $(this).toggleClass('multiple_select_active'); //close dropdown if click inside <select> box
});
$(".multiple_select").on('blur', function(e) {
    $(this).removeClass('multiple_select_active'); //close dropdown if click outside <select>
});
	
$('.multiple_select option').mousedown(function(e) { //no ctrl to select multiple
    e.preventDefault(); 
    $(this).prop('selected', $(this).prop('selected') ? false : true); //set selected options on click
    $(this).parent().change(); //trigger change event
});

	
	$("#myFilter").on('change', function() {
      var selected = $("#myFilter").val().toString(); //here I get all options and convert to string
      var document_style = document.documentElement.style;
      if(selected !== "")
        document_style.setProperty('--text', "'Selected: "+selected+"'");
      else
        document_style.setProperty('--text', "'Select values'");
	});
:root
{
	--text: "Select values";
}
.multiple_select
{
	height: 18px;
	width: 90%;
	overflow: hidden;
	-webkit-appearance: menulist;
	position: relative;
}
.multiple_select::before
{
	content: var(--text);
	display: block;
  margin-left: 5px;
  margin-bottom: 2px;
}
.multiple_select_active
{
	overflow: visible !important;
}
.multiple_select option
{
	display: none;
    height: 18px;
	background-color: white;
}
.multiple_select_active option
{
	display: block;
}

.multiple_select option::before {
  content: "\2610";
}
.multiple_select option:checked::before {
  content: "\2611";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="myFilter" class="multiple_select" multiple>
  <option>A</option>
  <option>B</option>
  <option>C</option>
  <option>D</option>
  <option>E</option>
</select>

于 2019-04-08T16:24:49.337 回答
2

为此,您可以在 git 上使用此库 https://github.com/ehynds/jquery-ui-multiselect-widget

启动选择框使用这个

    $("#selectBoxId").multiselect().multiselectfilter();

并且当您在 json 中准备好数据(来自 ajax 或任何方法)时,首先解析数据然后将 js 数组分配给它

    var js_arr = $.parseJSON(/*data from ajax*/);
    $("#selectBoxId").val(js_arr);
    $("#selectBoxId").multiselect("refresh");
于 2018-04-05T05:15:54.747 回答
2

将此代码用于选项菜单上的复选框列表。

.dropdown-menu input {
   margin-right: 10px;
}   
<div class="btn-group">
    <a href="#" class="btn btn-primary"><i class="fa fa-cogs"></i></a>
    <a href="#" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
      <span class="caret"></span>
    </a>
    <ul class="dropdown-menu" style="padding: 10px" id="myDiv">
        <li><p><input type="checkbox" value="id1" > OA Number</p></li>
        <li><p><input type="checkbox" value="id2" >Customer</p></li>
        <li><p><input type="checkbox" value="id3" > OA Date</p></li>
        <li><p><input type="checkbox" value="id4" >Product Code</p></li>
        <li><p><input type="checkbox" value="id5" >Name</p></li>
        <li><p><input type="checkbox" value="id6" >WI Number</p></li>
        <li><p><input type="checkbox" value="id7" >WI QTY</p></li>
        <li><p><input type="checkbox" value="id8" >Production QTY</p></li>
        <li><p><input type="checkbox" value="id9" >PD Sr.No (from-to)</p></li>
        <li><p><input type="checkbox" value="id10" > Production Date</p></li>
        <button class="btn btn-info" onClick="showTable();">Go</button>
    </ul>
</div>

于 2017-10-31T07:14:59.013 回答
1

您可以尝试Bootstrap-select。它也有实时搜索!

于 2019-12-26T09:17:34.133 回答
1

您可能会在使用 AJAX 调用更新选项列表之前加载 multiselect.js 文件,因此在执行 multiselect.js 文件时,有空的选项列表可以应用多选功能。因此,首先通过 AJAX 调用更新选项列表,然后启动多选调用,您将获得带有动态选项列表的下拉列表。

希望这会帮助你。

多选下拉列表相关的 js & css 文件

// This function should be called while loading page
var loadParentTaskList = function(){
    $.ajax({
        url: yoururl,
        method: 'POST',
        success: function(data){
            // To add options list coming from AJAX call multiselect
            for (var field in data) {
                $('<option value = "'+ data[field].name +'">' + data[field].name + '</option>').appendTo('#parent_task');
            }
   
            // To initiate the multiselect call 
            $("#parent_task").multiselect({
                includeSelectAllOption: true
            })
        }
    });
}
// Multiselect drop down list with id parent_task
<select id="parent_task" multiple="multiple">
</select>

于 2016-08-18T13:56:28.253 回答
0

如果要在同一页面中创建多个选择下拉菜单:

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

html:

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

使用jQuery:

 function showCheckboxes(elethis) {
        if($(elethis).next('#checkboxes').is(':hidden')){
            $(elethis).next('#checkboxes').show();
            $('.selectBox').not(elethis).next('#checkboxes').hide();  
        }else{
            $(elethis).next('#checkboxes').hide();
            $('.selectBox').not(elethis).next('#checkboxes').hide();
        }
 }
于 2019-10-25T06:05:53.243 回答
-2

仅添加类创建 div 并添加类表单控件。我使用 JSP,boostrap4。忽略 c:foreach。

<div class="multi-select form-control" style="height:107.292px;">
        <div class="checkbox" id="checkbox-expedientes">
            <c:forEach var="item" items="${postulantes}">
                <label class="form-check-label">
                    <input id="options" class="postulantes" type="checkbox" value="1">Option 1</label>
            </c:forEach>
        </div>
    </div>
于 2019-09-07T18:21:30.460 回答