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

user1614862 picture user1614862 · Apr 18, 2016 · Viewed 79.2k times · Source

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/

Answer

Shady Alset picture Shady Alset · Apr 18, 2016

Part #1 of Q:

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

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

Part #2 of Q:

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");
});

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

Edit #1

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

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

on Button:

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

Updated Fiddle #2