问题描述
Iam使用“ select2.min.js” js文件处理多选下拉列表
它工作正常,但是我想在已选择的项目之间选择项目,即在附加的屏幕快照中,我想通过在它们之间单击而不是删除“ dddd”来在“ BBBB”和“ dddd”之间添加“ AAAA”和“ FFFF”。
作为我们的要求,我需要将此作为必填项。谁能帮上忙,或者建议其他方式做
解决方法
要在单击的部分中添加选项(在另一个已选择的选项之前或之后),您需要:
- 收听选项列表中的点击事件
- 在select2上:选择将元素放置在正确的位置
$('.js-example-basic-multiple').select2().on('select2:select',function (e) {
var aferEle = $(this).data('select2').$container.data('spanafter');
var element = e.params.data.element;
var $element = $(element);
$element.detach();
if (aferEle == null) {
$(this).append($element);
} else {
$element.insertAfter($(this).find('option:contains("' + aferEle + '")'));
}
$(this).trigger("change");
}).data('select2').$container.on('click',function (e) {
var spans = $(this).find('.select2-selection__choice').filter(function (idx,ele) {
var x = ele.offsetLeft + ele.offsetWidth;
var y = e.clientX;
return x < y;
});
var spanafter = null;
if (spans.length < $(this).find('.select2-selection__choice').length) {
spanafter = spans.eq(spans.length-1).find('span:last').text();
}
$(this).data('spanafter',spanafter);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<select class="js-example-basic-multiple" name="states[]" multiple="multiple" style="width: 100%;">
<option>EEE</option>
<option>CCC</option>
<option>AAA</option>
<option>BBB</option>
<option>DDD</option>
<option>FFF</option>
</select>