jQuery 如何从select2多选中的选项列表中删除所选选项并按选择顺序显示所选选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36682901/
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-26 17:06:21  来源:igfitidea点击:

How to remove selected option from the option list in select2 multiselect and show selected options in the order they are selected

jqueryjquery-select2select2

提问by user1614862

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.

我的表单中有 select2 多选字段,我想在选择后从下拉列表中删除所选选项,如果它从列表中删除,则再次将其添加到列表中。而且添加的项目应该与他们选择的顺序相同。当前的 select2 (4.0) 没有删除选定的项目,而是按照它们在下拉列表中出现的顺序显示所选项目,而不是按照它们被选择的顺序。

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

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

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

回答by Shady Alset

Part #1 of Q:

问的第 1 部分:

You can do a CSS trickto hide selected itemlike this:

你可以做一个CSS 技巧selected item像这样隐藏:

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

Part #2 of Q:

问的第 2 部分:

Also you can do a JQuery trickto force selected itemsto 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 ):

你也可以做一个JQuery 技巧来强制selected items结束标签框,(通过在选择上获取选定的项目,分离它(删除它),然后将它重新附加到标签框,然后调用“更改函数”来应用更改)

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

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

终于更新了JsFiddle我希望它对你有用,谢谢!

Edit #1

编辑 #1

You can Clear All Selectedby this call (apply Null values):

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

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

on Button:

在按钮上:

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

Updated Fiddle #2

更新小提琴 #2

回答by Oli Soproni B.

I find a way to make the selected values not to appear anymore on the selection pop up list

我找到了一种方法,使选定的值不再出现在选择弹出列表中

On the documentation you can they have list of events Select2 events

在文档中,您可以查看事件列表Select2 事件

open

打开

I make use of these select2 event open to hide the selected values

我利用这些 select2 事件打开来隐藏选定的值

Here is the javascript ::

这是javascript ::

$(document).ready(function() {

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

  // override the select2 open event
  $('#dynamicAttributes').on('select2:open', function () {
    // get values of selected option
    var values = $(this).val();
    // get the pop up selection
    var pop_up_selection = $('.select2-results__options');

    if (values != null ) {
      // hide the selected values
       pop_up_selection.find("li[aria-selected=true]").hide();

    } else {
      // show all the selection values
      pop_up_selection.find("li[aria-selected=true]").show();
    }

  });

});

Here is a DEMO

这是一个演示

Hope it helps.

希望能帮助到你。

回答by Javier

my solution was modified the select2.js (the core, version 4.0.3) in the line #3158. Add the following verification :

我的解决方案是修改了 #3158 行中的 select2.js(核心,版本 4.0.3)。添加以下验证:

if ($option[0].selected == true) {
      return;
}

With this verification, we can exclude from the dropdown list, the selected ones. And if you write the name of a selected option, appear the text of option "noResult" .

通过此验证,我们可以从下拉列表中排除所选的。如果您写下所选选项的名称,则会出现选项 "noResult" 的文本。

Here the complete code:

这里是完整的代码:

SelectAdapter.prototype.query = function (params, callback) {
    var data = [];
    var self = this;

    var $options = this.$element.children();

    $options.each(function () {
      var $option = $(this);    
      if (!$option.is('option') && !$option.is('optgroup') ) {
        return;
      }

      if ($option[0].selected == true) {
           return;
      }

      var option = self.item($option);    
      var matches = self.matches(params, option);    
      if (matches !== null) {
        data.push(matches);
      }
    });

    callback({
      results: data
    });
  };

回答by fyrye

Another approach to hide the selected values, is to use the dropdown templateResultoption to return nullwhen the value is marked as selected.

隐藏选定值的另一种方法是在值标记为选定时使用下拉模板结果选项return null

function hideSelected(value) {
  if (value && !value.selected) {
    return $('<span>' + value.text + '</span>');
  }
}

$(document).ready(function() {
  $('#dynamicAttributes').select2({
    allowClear: true,
    placeholder: {
      id: "",
      placeholder: "Leave blank to ..."
    },
    minimumResultsForSearch: -1,
    width: 600,
    templateResult: hideSelected,
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/js/select2.min.js"></script>

<select id="dynamicAttributes" multiple="true" data-tags="true">
  <option value="1">A</option>
  <option value="2">B</option>
  <option value="3">C</option>
</select>

回答by amir taghavi

Remove (UnSelect) item from select2 multiple selected items

从 select2 多个选定项目中删除 (UnSelect) 项目

first step: add 'multiple' css class to your select2 element to get the true element which you want

第一步:将 'multiple' css 类添加到您的 select2 元素以获得您想要的真实元素

<select class="multiple">
....
</select>

    $('select.multiple').on('select2:selecting', function (e) {
        var select = this;
        var idToRemove = '0';
        var selections = $(select).select2('data');

        var Values = new Array();

        for (var i = 0; i < selections.length; i++) {
            if (idToRemove !== selections[i].id) {
                Values.push(selections[i].id);
            }
        }
        $(select).val(Values).trigger('change');
    });

回答by Avat Rezaei

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

this make a error when click the remove sign button

单击删除符号按钮时会出错

TypeError: this.placeholder is undefined

类型错误:this.placeholder 未定义

use

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

      });
});

回答by keerthana

$("#cqte").select2("val", "");
//cqte is id of dropdown