Selectable optgroup using select2

后端 未结 8 598
醉话见心
醉话见心 2020-12-02 21:20

I have used select2 to select multiple options from a drop down, but is it possible for select2 to select the full optgroup?? What I want is when user select the option grou

8条回答
  •  一生所求
    2020-12-02 21:57

    John S, provided example works really well (for V3) for most of the cases. However it has one bug:

    Assuming the selection list is long enough to have scroll. When you select any item in any group that is only available after you scroll down - you can't select the next item after the one you selected from this group anymore. It is because ensureHighlightVisible method of select2 starts misbehaving because the selectors it is using made using assumptions that group is always 'unselectable'. So the scroll will jump every time you try to select the item.

    So unfortunately although this solution looks really good - I dropped it and re-implemented it without using group id's:

    $selectEl..on("select2-open", function(event) {
              $(event.target).data("select2").dropdown.on("click", "li.select2-result-unselectable", selectGroup);
              $(event.target).data("select2").dropdown.on("mousemove-filtered", "li.select2-result-unselectable", highlight);
            }).on("select2-close", function(event) {
              $(event.target).data("select2").dropdown.off("click", "li.select2-result-unselectable", selectGroup);
              $(event.target).data("select2").dropdown.off("mousemove-filtered", "li.select2-result-unselectable", highlight);
            });
    

    and

      // selection of the group.
      function selectGroup(e) {
        var $li = $(this);
        e.preventDefault();
        $select.select2('data', $select.select2('data').concat($li.data("select2Data").children));
        $select.select2('close');
        _this.$field.trigger('change');
      }
    
      // highlight of the group.
      function highlight(e) {
        if ($(e.target).hasClass("select2-result-unselectable") || $(e.target.parentNode).hasClass('select2-result-unselectable')) {
          e.preventDefault();
          e.stopPropagation();
          $select.data("select2").dropdown.find(".select2-highlighted").removeClass("select2-highlighted");
          $(this).addClass("select2-highlighted");
        }
      }
    

提交回复
热议问题