Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selectable optgroups in Select2

I want to create multilevel select2 options with indentation but I don't want to use optgroup elements for this because I want to allow select also main categories. Is there any way to style if for select2?

My raw HTML select looks like this:

<select class="js-select-multiple">
  <option class="l1">Option 1</option>
  <option class="l2">Suboption 1</option>
  <option class="l2">Suboption 2</option>
  <option class="l2">Suboption 3</option>
  <option class="l1">Option 2</option>
  ...
</select>
<script>$(".js-select-multiple").select2({maximumSelectionLength: 5});</script>

So without using Select2 I can add text-indent property to .l2 class. However it seems that Select2 doesn't use those classes that are used for option, so styling those classes won't work.

Is there any workaround for that?

like image 524
Marcin Nabiałek Avatar asked Jun 13 '15 15:06

Marcin Nabiałek


1 Answers

You're correct in recognizing that Select2 does not carry the CSS classes from the <option> tags to the results list. This mostly has to do with not explicitly tying the results list to existing <option> tags, and also having a set of sensible defaults. It's easier to add the ability to transfer classes afterwards than it is to remove them.

You can do this by overriding templateResult and getting the original option from data.element (where data is the first parameter).

$('.select2').select2({
  templateResult: function (data) {    
    // We only really care if there is an element to pull classes from
    if (!data.element) {
      return data.text;
    }

    var $element = $(data.element);

    var $wrapper = $('<span></span>');
    $wrapper.addClass($element[0].className);

    $wrapper.text(data.text);

    return $wrapper;
  }
});
.l2 {
  padding-left: 1em;
}
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.js"></script>

<select class="select2" style="width: 200px">
  <option class="l1">Option 1</option>
  <option class="l2">Suboption 1</option>
  <option class="l2">Suboption 2</option>
  <option class="l2">Suboption 3</option>
  <option class="l1">Option 2</option>
</select>

Note that I am also using padding-left instead of text-indent, which is what Select2 usually uses for nested options.

like image 169
Kevin Brown-Silva Avatar answered Sep 28 '22 07:09

Kevin Brown-Silva