Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use different colors for each select2 option?

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.

like image 604
foob.ar Avatar asked Apr 12 '18 16:04

foob.ar


People also ask

How do I create a select2 dynamically?

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.

How do I add options in select2?

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).


1 Answers

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>
like image 71
unloco Avatar answered Oct 05 '22 23:10

unloco