2

I am using select2 to populate an HTML select, I want select2 options to have same background color as html select control options, is there any option in select2JS that allow us to do it or I have to do it manually?

Here is the sample code

$('.selectcls').select2({
  minimumResultsForSearch: -1,
  placeholder: "Nothing selected",
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.js"></script>

<div>
  <select id="select1" class="selectcls" style="width:100px" name="select1this" class="wrap">
        <option></option>
        <option style="background-color:green" value="A21">A21</option>
        <option style="background-color:blue" selected value="A22">A22</option>
        <option style="background-color:orange" value="A23">A23</option>
      </select>

</div>

or

jsfiddle

Jithin Raj P R
  • 6,427
  • 8
  • 36
  • 67
Addy
  • 2,808
  • 11
  • 53
  • 108

4 Answers4

2

You can specify whatever styles you want in your select2.css for Eg. I've overridden highlighted color from blue to yellowgreen

.select2-container--default .select2-results__option--highlighted[aria-selected] {
    background-color: yellowgreen;
    color: white;
}
Hiral
  • 119
  • 8
1

You can use in this way,

.select2-results ul li {
    background-color: red;
}

If you want to try different color in different options. Then use CSS3 child property like li:nth-child(<child number>).

  • 1
    Nice **CSS** solution bro and also if he wants to style `odd` or `even` options, then he can also use `:nth-child(odd)` or `:nth-child(even)` also. :) – Jithin Raj P R Aug 23 '17 at 09:23
  • cant change it using css as html is generated dynamically, I never know how many select items will be there and with which colors in their options. – Addy Aug 23 '17 at 11:26
  • From your example, you should know. But If you really don't then how are you gonna select color for an individual? – Mohammad Ashraful Islam Aug 23 '17 at 15:24
  • Done by using "select2:open" event, assigned
  • , ..!
  • – Addy Aug 24 '17 at 04:07