Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

jquery - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...