Select2 带有用于多选的复选框列表
Posted
技术标签:
【中文标题】Select2 带有用于多选的复选框列表【英文标题】:Select2 with a checkbox list for a multiple select 【发布时间】:2014-05-20 00:51:56 【问题描述】:我需要实现一个类似于这个http://www.erichynds.com/examples/jquery-ui-multiselect-widget/demos/的选择
我想为此使用 select2,但我无法从 select2 的创建者那里找到任何支持这种带有复选框的下拉样式的内容。有谁知道这样做的方法吗?
【问题讨论】:
这会让你感兴趣。 davidstutz.github.io/bootstrap-multiselect 【参考方案1】:我也遇到过类似的需求,但找不到。
我遇到的解决方案是使用标志 closeOnSelect 设置为 false
$("#yadayada").select2(closeOnSelect:false);
http://jsfiddle.net/jEADR/521/
【讨论】:
【参考方案2】:这似乎是旧帖子,但由于这是一个非常常见的问题,所以我在这里发布。
我发现作者已经在 select2 中添加了一个插件,以便该功能具有类似于复选框的选择,并且下拉菜单在单击时不会隐藏:
https://github.com/wasikuss/select2-multi-checkboxes
例子:
$('.select2-multiple').select2MultiCheckboxes(
placeholder: "Choose multiple elements",
)
http://jsfiddle.net/wasikuss/gx93rwnk/
select2 的所有其他功能都被保留。还有几个预定义的选项设置可以正常工作。
【讨论】:
它不适用于 Select2 4.0.x。感谢您提供此示例,但您使用的是 3.5.4。我用 4.0.x 创建了一个小提琴和一个关于多复选框的问题:***.com/questions/52263430/… 4.x版本有更新:github.com/wasikuss/select2-multi-checkboxes/tree/amd【参考方案3】:我设法把一些东西放在一起,虽然不完美,但它确实有效。
https://jsfiddle.net/Lkkm2L48/7/
jQuery(function($)
$.fn.select2.amd.require([
'select2/selection/single',
'select2/selection/placeholder',
'select2/selection/allowClear',
'select2/dropdown',
'select2/dropdown/search',
'select2/dropdown/attachBody',
'select2/utils'
], function (SingleSelection, Placeholder, AllowClear, Dropdown, DropdownSearch, AttachBody, Utils)
var SelectionAdapter = Utils.Decorate(
SingleSelection,
Placeholder
);
SelectionAdapter = Utils.Decorate(
SelectionAdapter,
AllowClear
);
var DropdownAdapter = Utils.Decorate(
Utils.Decorate(
Dropdown,
DropdownSearch
),
AttachBody
);
var base_element = $('.select2-multiple2')
$(base_element).select2(
placeholder: 'Select multiple items',
selectionAdapter: SelectionAdapter,
dropdownAdapter: DropdownAdapter,
allowClear: true,
templateResult: function (data)
if (!data.id) return data.text;
var $res = $('<div></div>');
$res.text(data.text);
$res.addClass('wrap');
return $res;
,
templateSelection: function (data)
if (!data.id) return data.text;
var selected = ($(base_element).val() || []).length;
var total = $('option', $(base_element)).length;
return "Selected " + selected + " of " + total;
)
);
);
CSS:
.select2-results__option .wrap:before
font-family:fontAwesome;
color:#999;
content:"\f096";
width:25px;
height:25px;
padding-right: 10px;
.select2-results__option[aria-selected=true] .wrap:before
content:"\f14a";
【讨论】:
【参考方案4】:用 css 只添加两个表情符号
.select2-results__options
&[aria-multiselectable=true]
.select2-results__option
&[aria-selected=true]:before
content: '☑';
padding: 0 0 0 4px;
&:before
content: '◻';
padding: 0 0 0 4px;
您会看到此示例是带有基于表情符号的复选框的 RTL select2
【讨论】:
【参考方案5】:这里是非常简单的sn-p,没有对js进行奇怪的修改——纯粹简单的css(带“Font Awesome”)
$('.select2[multiple]').select2(
width: '100%',
closeOnSelect: false
)
#body
padding: 30px
.select2-results__options[aria-multiselectable="true"] li
padding-left: 30px;
position: relative
.select2-results__options[aria-multiselectable="true"] li:before
position: absolute;
left: 8px;
opacity: .6;
top: 6px;
font-family: "FontAwesome";
content: "\f0c8";
.select2-results__options[aria-multiselectable="true"] li[aria-selected="true"]:before
content: "\f14a";
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/js/all.min.js"></script>
<div id="body">
<select name="fabric_color_en[]" id="fabric_color_en[]" multiple="multiple" class="form-control select2">
<option value="Beige">
Beige
</option>
<option value="Red">
Red
</option>
<option value="Petrol">
Petrol
</option>
<option value="Royal Blue">
Royal Blue
</option>
<option value="Dark Blue">
Dark Blue
</option>
<option value="Bottle Green">
Bottle Green
</option>
<option value="Light Grey">
Light Grey
</option>
</select>
</div>
【讨论】:
【参考方案6】:现在代码已准备好用于实现多个复选框 select2 下拉菜单。
享受 :) //================================================
//Start - Select 2 Multi-Select Code======================================================
var Select2MultiCheckBoxObj = [];
var id_selectElement = 'id_SelectElement';
var staticWordInID = 'state_';
function AddItemInSelect2MultiCheckBoxObj(id, IsChecked)
if (Select2MultiCheckBoxObj.length > 0)
let index = Select2MultiCheckBoxObj.findIndex(x => x.id == id);
if (index > -1)
Select2MultiCheckBoxObj[index]["IsChecked"] = IsChecked;
else
Select2MultiCheckBoxObj.push( "id": id, "IsChecked": IsChecked );
else
Select2MultiCheckBoxObj.push( "id": id, "IsChecked": IsChecked );
function IsCheckedAllOption(trueOrFalse)
$.map($('#' + id_selectElement + ' option'), function (option)
AddItemInSelect2MultiCheckBoxObj(option.value, trueOrFalse);
);
$('#' + id_selectElement + " > option").not(':first').prop("selected", trueOrFalse); //This will select all options and adds in Select2
$("#" + id_selectElement).trigger("change");//This will effect the changes
$(".select2-results__option").not(':first').attr("aria-selected", trueOrFalse); //This will make grey color of selected options
$("input[id^='" + staticWordInID + "']").prop("checked", trueOrFalse);
$(document).ready(function ()
//Begin - Select 2 Multi-Select Code
$.map($('#' + id_selectElement + ' option'), function (option)
AddItemInSelect2MultiCheckBoxObj(option.value, false);
);
function formatResult(state)
if (Select2MultiCheckBoxObj.length > 0)
var stateId = staticWordInID + state.id;
let index = Select2MultiCheckBoxObj.findIndex(x => x.id == state.id);
if (index > -1)
var checkbox = $('<div class="checkbox"><input class="select2Checkbox" id="' + stateId + '" type="checkbox" ' + (Select2MultiCheckBoxObj[index]["IsChecked"] ? 'checked' : '') +
'><label for="checkbox' + stateId + '">' + state.text + '</label></div>', id: stateId );
return checkbox;
let optionSelect2 =
templateResult: formatResult,
closeOnSelect: false,
width: '100%'
;
let $select2 = $("#" + id_selectElement).select2(optionSelect2);
//var scrollTop;
//$select2.on("select2:selecting", function (event)
// var $pr = $('#' + event.params.args.data._resultId).parent();
// scrollTop = $pr.prop('scrollTop');
// let xxxx = 2;
//);
$select2.on("select2:select", function (event)
$("#" + staticWordInID + event.params.data.id).prop("checked", true);
AddItemInSelect2MultiCheckBoxObj(event.params.data.id, true);
//If all options are slected then selectAll option would be also selected.
if (Select2MultiCheckBoxObj.filter(x => x.IsChecked === false).length === 1)
AddItemInSelect2MultiCheckBoxObj(0, true);
$("#" + staticWordInID + "0").prop("checked", true);
);
$select2.on("select2:unselect", function (event)
$("#" + staticWordInID + "0").prop("checked", false);
AddItemInSelect2MultiCheckBoxObj(0, false);
$("#" + staticWordInID + event.params.data.id).prop("checked", false);
AddItemInSelect2MultiCheckBoxObj(event.params.data.id, false);
);
$(document).on("click", "#" + staticWordInID + "0", function ()
//var b = !($("#state_SelectAll").is(':checked'));
var b = $("#" + staticWordInID + "0").is(':checked');
IsCheckedAllOption(b);
//state_CheckAll = b;
//$(window).scroll();
);
$(document).on("click", ".select2Checkbox", function (event)
let selector = "#" + this.id;
let isChecked = Select2MultiCheckBoxObj[Select2MultiCheckBoxObj.findIndex(x => x.id == this.id.replaceAll(staticWordInID, ''))]['IsChecked'];
$(selector).prop("checked", isChecked);
);
);
//====End - Select 2 Multi-Select Code==
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js" integrity="undefined" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<div class="container-fluid">
<hr/>
<p>Here, you can select any item by clicking on row or checked in on checkbox and can unselect in reverse way.</p>
<p>But I didn't give the option to select "SelectAll" option by clicking on his row, you can select-all and unselect-all by click on checkbox only rather than row.</p>
<div class="row" style="width:50%">
<label for="id_SelectElement" class="col-sm-2">Part Name: </label>
<div class="col-sm-4">
<select id="id_SelectElement" placeholder="Select Text" multiple>
<option value="0" disabled>Select All</option>
<option value="11">php</option>
<option value="22">Bootstrap</option>
<option value="33">sql</option>
<option value="44">Node Js</option>
<option value="55">Laravel</option>
<option value="66">Jquery</option>
<option value="77">React</option>
<option value="88">Vew.JS</option>
<option value="99">MVC</option>
<option value="10">DotNetCore</option>
<option value="12">Java</option>
<option value="13">Artifical Intiligence</option>
<option value="14">Data Structure</option>
<option value="15">Data Science</option>
<option value="16">Robotics</option>
<option value="17">Node Js 2</option>
<option value="18">Laravel 23</option>
<option value="19">Jquery 3.4</option>
</select>
</div>
</div>
</div>
【讨论】:
【参考方案7】:另一种解决方法是使用 CSS “预先”添加复选框图标。我使用引导主题 - 您的 select2-container 可能不同。
.select2-container--bootstrap .select2-results__option[aria-selected=true]:before content:'\e067 '; padding:0 8px 0 0px; font-family:'Glyphicons Halflings'
.select2-container--bootstrap .select2-results__option:before content:'\e157 '; padding:0 8px 0 0px; font-family:'Glyphicons Halflings'
【讨论】:
以上是关于Select2 带有用于多选的复选框列表的主要内容,如果未能解决你的问题,请参考以下文章