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

前端 未结 7 1287
一生所求
一生所求 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 08:57

    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

    open

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

    Here is the 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.

提交回复
热议问题