Остановить Select2 при закрытии выпадающего меню после отметки Select All - PullRequest
0 голосов
/ 29 мая 2018

Я пытаюсь остановить закрытие раскрывающегося списка select2 после того, как я установил флажок «Выбрать все».После прочтения постов я вижу, что могу с помощью форсировки .select2 ('open');но это хак и визуально плохой.

После сообщений я также пытался использовать stopPropagation () в событии клика «Выбрать все», но это, кажется, игнорируется (иначе я не использую его)право).Я еще не видел пример в сообщениях о случае, когда раскрывающийся список остается открытым после выбора всех параметров.

У кого-нибудь есть идеи?

<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"></script>


<body class='bodyClass'>

  <div class="CountryDropContainer">

    <div id="Container_selectAll">
      <label id='#Outer_selectAll'>
  <input id="selectAll" type='checkbox'>
  <span></span>
  All
</label>
    </div>

    <select id="CountryBoxesContainerID_prodn" name="CountryBoxesContainerID_prodn" class="form-control select2-multiple" multiple="multiple">

<option class="myEuropeCountries" value="UN208a" title="Denmark" >Denmark</option>
<option class="myEuropeCountries" value="UN233a" title="Estonia" >Estonia</option>
<option class="myEuropeCountries" value="UN246a" title="Finland" >Finland</option>
<option class="myEuropeCountries" value="UN348a" title="Hungary" >Hungary</option>
<option class="myEuropeCountries" value="UN352a" title="Iceland" >Iceland</option>

</select>
  </div>
</body>

.

$(function() {

  var S2MultiCheckboxes = function(options, element) {
    var self = this;
    self.options = options;
    self.$element = $(element);
    var values = self.$element.val();
    self.$element.removeAttr('multiple');
    self.select2 = self.$element.select2({

      allowClear: true, 
      placeholder: options.placeholder,
      closeOnSelect: false,

      templateSelection: function() {
        return self.options.templateSelection(self.$element.val() || [], $('option', self.$element).length);
      },
      templateResult: function(result) {
        if (result.loading !== undefined)
          return result.text;
        return $('<div>').text(result.text).addClass(self.options.wrapClass);
      }
    }).data('select2');
    self.select2.$results.off("mouseup").on("mouseup", ".select2-results__option[aria-selected]", (function(self) {
      return function(evt) {
        var $this = $(this);

        var data = $this.data('data');

        if ($this.attr('aria-selected') === 'true') {
          self.trigger('unselect', {
            originalEvent: evt,
            data: data
          });
          return;
        }

        self.trigger('select', {
          originalEvent: evt,
          data: data
        });
      }
    })(self.select2));
    self.$element.attr('multiple', 'multiple').val(values).trigger('change.select2');
  }

  // -----------------

  $.fn.extend({
    select2MultiCheckboxes: function() {
      var options = $.extend({
        wrapClass: 'wrap'
      }, arguments[0]);

      this.each(function() {
        new S2MultiCheckboxes(options, this);
      });
    }
  });


});



// ======================================

// Initialise dropdown
$(function() {

  //---------



  //---------


  $('#CountryBoxesContainerID_prodn').select2MultiCheckboxes({

    // placeholder: "",
    closeOnSelect: false,
    width: "auto",
    placeholder: '',
    escapeMarkup: function(markup) {
      return markup;
    },

    templateSelection: function(selected, total) {
      return ("Select Country" + ' ' + "") + selected.length + (" of ") + total + ("\xa0\xa0\xa0\xa0");
    },


  })


  //----------------------


  // When select2 is opened, show 'Select All' chkbx
  $('select').on('select2:open', function(e) {
    $('#Container_selectAll').css('display', 'block');
    $('#Container_selectAll').show();
  });


  // When select2 is closed
  $('select').on('select2:close', function(e) {
    //$('#Container_selectAll').hide();
  });



  // Detect click of an option 'ON'
  $("#selectAll").click(function() {

    if ($("#selectAll").is(':checked')) {

      $("#CountryBoxesContainerID_prodn > option").prop("selected", "selected");
      $("#CountryBoxesContainerID_prodn").trigger("change");
      //$('#CountryBoxesContainerID_prodn').select2('open');

    } else {
      $("#CountryBoxesContainerID_prodn > option").removeAttr("selected");
      $("#CountryBoxesContainerID_prodn").trigger("change");
      //$('#CountryBoxesContainerID_prodn').select2('open');
    }
  });


});

Скрипка: https://jsfiddle.net/x4eexqnc/

...