Select2 v4.0 make optgroups selectable

独自空忆成欢 提交于 2019-11-29 09:36:55
Kevin Brown

This was requested over on GitHub, but realistically it is not actually possible. It was previously possible with a <input />, but the switch to a <select> meant that we now explicitly disallow a selectable <optgroup>.


There is a technical barrier here that Select2 will likely never be able to tackle: A standard <optgroup> is not selectable in the browser. And because a data object with children is converted to an <optgroup> with a set of nested <option> elements, the problem applies in your case with the same issue.

The best possible solution is to have an <option> for selecting the group, like you would have with a standard select. Without an <option> tag, it's not possible to set the selected value to the group (as the value doesn't actually exist). Select2 even has a templateResult option (formatResult in 3.x) so you can style it as a group consistently across browsers.

I manage to achieve this by using the templateResult property and attaching click events to the optgroups in this way:

$('#my-select').select2({
    templateResult: function(item) {
    if(typeof item.children != 'undefined') {

        var s = $(item.element).find('option').length - $(item.element).find('option:selected').length;
        // My optgroup element
        var el = $('<span class="my_select2_optgroup'+(s ? '' : ' my_select2_optgroup_selected')+'">'+item.text+'</span>');

        // Click event
        el.click(function() {
        // Select all optgroup child if there aren't, else deselect all
        $('#my-select').find('optgroup[label="' + $(this).text() + '"] option').prop(
            'selected',
            $(item.element).find('option').length - $(item.element).find('option:selected').length
        );
        // Trigger change event + close dropdown
        $('#my-select').change();
        $('#my-select').select2('close');
        });

        // Hover events to properly manage display 
        el.mouseover(function() {
        $('li.select2-results__option--highlighted').removeClass('select2-results__option--highlighted');
        });
        el.hover(function() {
        el.addClass('my_select2_optgroup_hovered');
        }, function() {
        el.removeClass('my_select2_optgroup_hovered');
        });
        return el;
    }
    return item.text;
    }
});

And the associated css:

.my_select2_optgroup_selected {
    background-color: #ddd;
}
.my_select2_optgroup_hovered {
    color: #FFF;
    background-color: #5897fb !important;
    cursor: pointer;
}
strong.select2-results__group {
    padding: 0 !important;
}
.my_select2_optgroup {
    display: block;
    padding: 6px;
}

Well, I came across this issue and I found that every time the select2 (Select2 4.0.5) opens it adds a span element before the closing body element. In addition, inside the span element adds a ul with the id: select2-X-results, where X is the select2 id. So I found the following workaround (jsfiddle):

var countries = [{
  "id": 1,
  "text": "Greece",
  "children": [{
    "id": "Athens",
    "text": "Athens"
  }, {
    "id": "Thessalonica",
    "text": "Thessalonica"
  }]
}, {
  "id": 2,
  "text": "Italy",
  "children": [{
    "id": "Milan",
    "text": "Milan"
  }, {
    "id": "Rome",
    "text": "Rome"
  }]
}];

$('#selectcountry').select2({
  placeholder: "Please select cities",
  allowClear: true,
  width: '100%',
  data: countries
});

$('#selectcountry').on('select2:open', function(e) {

  $('#select2-selectcountry-results').on('click', function(event) {

    event.stopPropagation();
    var data = $(event.target).html();
    var selectedOptionGroup = data.toString().trim();

    var groupchildren = [];

    for (var i = 0; i < countries.length; i++) {


      if (selectedOptionGroup.toString() === countries[i].text.toString()) {

        for (var j = 0; j < countries[i].children.length; j++) {

          groupchildren.push(countries[i].children[j].id);

        }

      }


    }


    var options = [];

    options = $('#selectcountry').val();

    if (options === null || options === '') {

      options = [];

    }

    for (var i = 0; i < groupchildren.length; i++) {

      var count = 0;

      for (var j = 0; j < options.length; j++) {

        if (options[j].toString() === groupchildren[i].toString()) {

          count++;
          break;

        }

      }

      if (count === 0) {
        options.push(groupchildren[i].toString());
      }
    }

    $('#selectcountry').val(options);
    $('#selectcountry').trigger('change'); // Notify any JS components that the value changed
    $('#selectcountry').select2('close');    

  });
});
li.select2-results__option strong.select2-results__group:hover {
  background-color: #ddd;
  cursor: pointer;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.full.min.js"></script>


<h1>Selectable optgroup using select2</h1>
<select id="selectcountry" name="country[]" class="form-control" multiple style="width: 100%"></select>

$(document).ready(function() {
   $('#countrySelect').select2({
     data: [{
       text: "group",
       "id": 1,
       children: [{
         "text": "Test 2",
         "id": "2"
       }, {
         "text": "Test 3",
         "id": "3",
         "selected": true
       }]
     }]
   });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://select2.github.io/dist/js/select2.full.js"></script>
<link href="https://select2.github.io/dist/css/select2.min.css" rel="stylesheet" />


<select id="countrySelect" style="width: 380px;" placeholder="Select regions..."></select>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!