-1

I'm using a Select2 drop-down, and would like to set different colors on options. I successfully changed all options to one color, but I want to variate between several ones basing on the value. I have close to 1000 options (pages in books) and I need to mark some of them (based on some set of pages) as green. May you propose the way to achieve this?

HTML

<label for="add-coord-page">P:  </label>
<select class="select2" id="add-coord-page" name="pages" style="width:60px"></select>

CSS

#select2-add-coord-page-results { 
    color: red;
}

Example: Expected result

Solo
  • 3
  • 3
  • 1
    it would be helpful if you posted a minimally reproducible example for what you've developed so far – M Z Aug 18 '20 at 14:18
  • Thanks. I added some code, but the task is better examplifed by the attached picture. – Solo Aug 18 '20 at 14:37
  • Does this answer your question? [Change select box option background color](https://stackoverflow.com/questions/12836227/change-select-box-option-background-color) – Lain Aug 18 '20 at 14:39
  • Read it before. Not exactly what I need. Looking for cleaner way. – Solo Aug 18 '20 at 15:07
  • This is what answers my answer completely. https://stackoverflow.com/questions/36360783/how-to-render-html-in-select2-options Most useful. – Solo Sep 06 '20 at 09:55

2 Answers2

0

Use the nth-child on the option tag

<style>
    option:nth-child(odd) {
        color: red;
    }
    option:nth-child(even) {
        color: green;
    }
</style>
<select>
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
    <option>Option 4</option>
    <option>Option 5</option>
    <option>Option 6</option>
</select>
Dan Mullin
  • 4,285
  • 2
  • 18
  • 34
  • Very close, thanks Dan! Unfortunately, it is not exactly - odd/even. I have close to 1000 options (pages in books) and I need to mark some of them (based on some set of pages) as green. – Solo Aug 18 '20 at 15:01
0

Solved! The main problem was that selection2 dropdown options are created dynamically and no event is generated on it. That is the trick.

  1. I marked all the pages that were supposed to change color by adding space.

  2. Then on relevant event:

     // Set colors of pages containing images
     $('#add-coord-page').on('select2:open', function (e) {
    
         setTimeout(function () {
             $('.select2-results__option:contains(" ")').css('color', SUCCESS_COLOR);
         }, 100);
    
     });
    

The timer places function changing color on the events loop. Thanks everyone who tried help me.

Solo
  • 3
  • 3