Selectable optgroups in Select2
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.
Marcin Nabiałek
I'm a Cerified Laravel Developer & Zend Certified PHP Engineer experienced in making code reviews. If you need remote Laravel PHP developer or you are looking for someone to help you to keep high code quality, feel free to contact. Learn more about me at Marcin Nabiałek - Laravel PHP developer
Updated on July 09, 2022Comments
-
Marcin Nabiałek almost 2 years
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 thatSelect2
doesn't use those classes that are used for option, so styling those classes won't work.Is there any workaround for that?
-
adam78 about 8 yearsThe search box wouldn't work very well using this method. E.g. if you add Suboption 4 under option 2 and searched for
sub
you won't know which category the suboptions belong to since level 1 categories would be excluded from the results.