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

前端 未结 7 1306
一生所求
一生所求 2021-02-02 08:19

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

7条回答
  •  醉酒成梦
    2021-02-02 09:03

    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

提交回复
热议问题