I would like to have Select2 include all the CSS classes of the original source in its selection and results drop-down rendering.
This solution uses the templateResult option and works for the results drop-down. It seems to work when I use the same code for templateSelection as suggested in the next answer, but there is a problem:
function copyClassesToSelect2(data, container) {
if (data.element) {
$(container).addClass($(data.element).attr("class"));
}
return data.text;
}
(function ($) {
"use strict";
$(function () {
$("#my-select").select2({
allowClear: true,
minimumResultsForSearch: Infinity,
templateResult: copyClassesToSelect2,
templateSelection: copyClassesToSelect2
});
});
}(jQuery));
.one {background: cyan}
.two {background: yellow}
.three {background: lightgreen}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script>
<select id="my-select" class="my-select" name="my-select" data-placeholder="--- Please select ---">
<option value="">--- Please select ---</option>
<option value="one" class="one">One</option>
<option value="two" class="two">Two</option>
<option value="three" class="three">Three</option>
</select>
When changing the selection, the rendered selected item keeps all the previously attached classes. Therefore, when selecting "one" or "two" after "three", they both stay green instead of their respective color. Also, when clearing the selection, the placeholder has the green background.
How would I need to modify the
templateSelectioncallback to make the selected item only have the desired class?Would the hardly documented options
adaptContainerCssClassandadaptDropdownCssClassbe of any help here? What do they do?Is there a better approach to make Select2 inherit all the original source attributes, for example
class="my-select"from the original<select>?