Html 如何在 Select Option 中使用 Checkbox

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17714705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 11:16:23  来源:igfitidea点击:

How to use Checkbox inside Select Option

javascripthtmlcsshtml-select

提问by Hero Tra

The client has given me a design which has a Select Option menu containing a checkbox together with the item name as individual items in the list. Is there anyway possible to add a checkbox inside a Select Option menu?

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

NB: Developer needs to add his own id to make the menu effective, I only need the HTML CSS code if it is possible.

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

回答by vitfo

You cannot place checkbox inside select element but you can get the same functionality by using HTML, CSS and JavaScript. Here is a possible working solution. The explanation follows.

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

enter image description here

在此处输入图片说明



Code:

代码:

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>

Explanation:

解释:

At first we create a select element that shows text "Select an option", and empty element that covers (overlaps) the select element (<div class="overSelect">). We do not want the user to click on the select element - it would show an empty options. To overlap the element with other element we use CSS position property with value relative | absolute.

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

To add the functionality we specify a JavaScript function that is called when the user clicks on the div that contains our select element (<div class="selectBox" onclick="showCheckboxes()">).

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

We also create div that contains our checkboxes and style it using CSS. The above mentioned JavaScript function just changes <div id="checkboxes">value of CSS display property from "none" to "block" and vice versa.

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

The solution was tested in the following browsers: Internet Explorer 10, Firefox 34, Chrome 39. The browser needs to have JavaScript enabled.

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



More information:

更多信息:

CSS positioning

CSS定位

How to overlay one div over another div

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

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

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

CSS display property

CSS 显示属性

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

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

回答by pmrotule

The best plugin so far is Bootstrap Multiselect

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

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

Here's the DEMO

这是演示

$(function() {

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

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

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

回答by KyleMit

For a Pure CSSapproach, you can use the :checkedselector combined with the ::beforeselector to inline conditional content.

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

Just add the class select-checkboxto your selectelement and include the following CSS:

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

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

You can use plain old unicode characters (with an escaped hex encoding) like these:

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

Or if you want to spice things up, you can use these FontAwesomeglyphs

或者,如果你想给东西增添趣味,你可以使用这些FontAwesome字形

Screenshot

截屏

Demo in jsFiddle& Stack Snippets

jsFiddle& Stack Snippets 中的演示

select {
  width: 150px;
}

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

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

Note: Beware of IE compatibility issues however

注意但是要注意 IE 兼容性问题

回答by Azghanvi

Try multiple-select. Looks to be much clean and managed solution, with tons of examples.

尝试多选。看起来是非常干净和管理的解决方案,有大量的例子。

回答by pavelbere

I started from @vitfo answer but I want to have <option>inside <select>instead of checkbox inputs so i put together all the answers to make this, there is my code, I hope it will help someone.

我从@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: "10";
}
.multiple_select option:checked::before {
  content: "11";
}
<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>

回答by davidysoards

Alternate Vanilla JS version with click outside to hide checkboxes:

替代 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)

I'm using addEventListener instead of onClick in order to take advantage of the capture/bubbling phase options along with stopPropagation(). You can read more about the capture/bubbling here: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

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

The rest of the code matches vitfo's original answer (but no need for onclick() in the html). A couple of people have requested this functionality sans jQuery.

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

Here's codepen example https://codepen.io/davidysoards/pen/QXYYYa?editors=1010

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

回答by Jaya Parwani

You can use this library on git for this purpose https://github.com/ehynds/jquery-ui-multiselect-widget

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

for initiating the selectbox use this

启动选择框使用这个

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

and when you have the data ready in json (from ajax or any method), first parse the data & then assign the js array to it

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

    var js_arr = $.parseJSON(/*data from ajax*/);
    $("#selectBoxId").val(js_arr);
    $("#selectBoxId").multiselect("refresh");

回答by Rupesh Wankhede

Use this code for checkbox list on option menu.

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

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

回答by Yaswini Modupalli

You might be loading multiselect.js file before the option list updated with AJAX call so while execution of multiselect.js file there is empty option list is there to apply multiselect functionlaity. So first update the option list by AJAX call then initiate the multiselect call you will get the dropdown list with the dynamic option list.

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

Hope this will help you out.

希望这会帮助你。

Multiselect dropdown listand related js & css files

多选下拉列表相关的 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>

回答by Ashish

If you want to create multiple select dropdowns in the same page:

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

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

Using Jquery:

使用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();
        }
 }