Search code examples
groupingjquery-select2-4

Select2, need to group results into one for display


I use "multiple select boxes" (select2 examples) and I want to group showing results: enter image description here

like (only if selected more then X options):

enter image description here

Whithout this the field with the results will be too large. Also, I don't want to make a scroll in the field results.

Is there any ready solution to do this?


Solution

  • I created the solution:

    $(document).ready(function() {
      $(".test").select2();
    });
    function select_grouping(obj) {
      var min_grouping_count = 3;
      var title = ' elements selected';
      var count = 0;
      if (obj.children('li').length > min_grouping_count) {
        if (obj.children('li').length > min_grouping_count) {
          count = obj.children('li').length - 1;
          obj.children('li').each(function(index, el) {
            if (index > 0 && index < count) {
              $(this).remove();
            }
          });
        }
        obj.children('li:eq(0)').html(count + title);
      }
    }
    $(".test").on("select2:select", function(obj) {
      var obj = $('#filtr_test').find('.select2-selection__rendered');
      select_grouping(obj);
    });
    $(".test").on("select2:unselect", function(obj) {
      var obj = $('#filtr_test').find('.select2-selection__rendered');
      select_grouping(obj);
    });
    .test {
      width: 200px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
    <link href="http://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
    
    <div id="filtr_test">
      <select class="test" multiple="multiple">
        <option value="1">one</option>
        <option value="2">two</option>
        <option value="3">three</option>
        <option value="4">four</option>
        <option value="5">five</option>
        <option value="6">six</option>
        <option value="7">seven</option>
      </select>
    </div>