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

前端 未结 7 1389
一生所求
一生所求 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:50

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

    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" .

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

提交回复
热议问题