如何从select2多重选择的选项列表中删除选择的选项,并按选择的顺序显示选择的选项 [英] How to remove selected option from the option list in select2 multiselect and show selected options in the order they are selected

查看:411
本文介绍了如何从select2多重选择的选项列表中删除选择的选项,并按选择的顺序显示选择的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表单中有select2 multi select字段,在该字段中我想从下拉列表中删除所选选项,如果从列表中删除该选项,则再次将其添加到列表中.并且添加的项目应与选择的顺序相同.当前的select2(4.0)不会删除所选的项目,而是按所选项目在下拉列表中的显示顺序显示它们,而不是按所选顺序显示.

I have select2 multi select field in my form where I want to remove the selected option from the dropdown list after it is selected and again add it to the list if it is removed from the list. And also the added items should be in the same order as they selected. The current select2 (4.0) is not removing the selected the items and and it is showing the selected items in the order they appear in the drop down list, not in the order they are selected.

$(document).ready(function(){
    $('#dynamicAttributes').select2({
            allowClear: true,
            minimumResultsForSearch: -1,
            width: 600
     });
 });

JSFiddle: https://jsfiddle.net/rd62bhbm/

JSFiddle: https://jsfiddle.net/rd62bhbm/

推荐答案

问题的第1部分:

Part #1 of Q:

您可以执行 CSS技巧来隐藏selected item,如下所示:

You can do a CSS trick to hide selected item like this:

.select2-results__option[aria-selected=true] {
    display: none;
}

第2部分:

Part #2 of Q:

此外,您还可以执行 JQuery技巧,以强制selected items到标签框(通过选择选中项,将其分离(删除)),然后将其重新附加到标签框,然后调用更改功能"以应用更改):

Also you can do a JQuery trick to force selected items to end of tags box, ( by getting selected item on select, detach it (remove it), then reAppend it to tags box, then call "change function" to apply changes ):

$("select").on("select2:select", function (evt) {
    var element = evt.params.data.element;
    var $element = $(element);
    $element.detach();
    $(this).append($element);
    $(this).trigger("change");
});

最后更新了 JsFiddle 我希望它对您有用,谢谢! /em>

Finally Updated JsFiddle, I hope it works for you, Thanks !

编辑#1

Edit #1

您可以通过此调用Clear All Selected (应用空值):

$("#dynamicAttributes").val(null).trigger("change"); 

按钮上

$('#btnReset').click(function() {
    $("#dynamicAttributes").val(null).trigger("change"); 
});

更新的小提琴#2

这篇关于如何从select2多重选择的选项列表中删除选择的选项,并按选择的顺序显示选择的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆