AddyProg
AddyProg

Reputation: 3050

Select2 options background color same as html select

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

Upvotes: 2

Views: 13625

Answers (4)

PalakM
PalakM

Reputation: 321

With dynamic data you can take below approach.

let _colors = [
{
    "id": "#1CAC78",
    "text": "Green"
},
{
    "id": "#1F75FE",
    "text": "Blue"
},
{
    "id": "#FF7538",
    "text": "Orange"
}

And dropdown should be initialized with below code.

$("select").select2({
    templateResult: function (data, container) {
        if (data.element) {
            $(container).css({"background-color":data.id});
        }
        return data.text;
    },data:_colors
});

here is a fiddle for select2 option with background

Upvotes: 2

Rana Hyder
Rana Hyder

Reputation: 509

I answer in detail here https://stackoverflow.com/a/53059749/7582170

For combo box

.select2-container--default .select2-selection--single{
    background-color: #000;
}

For options search box

.select2-search--dropdown{
    background-color: #000;
}
.select2-search__field{
    background-color: #000;
}

and for options list

.select2-results { 
    background-color: #000;
}

Upvotes: 1

Hiral
Hiral

Reputation: 129

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;
}

Upvotes: 2

Ashraful
Ashraful

Reputation: 1964

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

Upvotes: 1

Related Questions