I'm using a select2 dropdown, and would like to set different colours on each options.
Example:
<select class="select2" name="fruit">
<option class="red-option">Apple</option>
<option class="green-option">Kiwi</option>
<option class="blue-option">Grape</option>
</select>
I can colourize the rendered, selected option as follow:
.select2-selection__rendered[title="Apple"] {
color: red !important;
}
How to also colourize the options in the select2 dropdown - either based on the option class ('red-option') or value ('Apple')?
PS: I use bootstrap 3.3 + jQuery and don't mind using JS to do this if I must.
Select2 jQuery plugin is easy to add on the <select > element. Need to call the select2() method on the selector to initialize. If you adding select2 on a class or select element and when you add an element dynamically then select2 is not initialized on that element.
New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2'). append(newOption).
I found a better solution using the options
function formatState(state) {
const option = $(state.element);
const color = option.data("color");
if (!color) {
return state.text;
}
return $(`<span style="color: ${color}">${state.text}</span>`);
};
jQuery(node).select2({
templateResult: formatState,
templateSelection: formatState,
});
The color comes from the html data attribute in my case
<option style="color: #F00" data-color="#F00" value="1">Red Option</option>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With