简体   繁体   中英

Changing font color of selected item by user with select2

I've simple select option html:

<select name="individual_taxCountry" id="individual_taxCountry" class="select2">
<option value="" selected="selected" class="selected">Select a country</option>
<option value="Afghanistan" >Afghanistan</option>
<option value="Aland Islands" >Aland Islands</option>
<option value="Albania" >Albania</option>
<option value="Algeria" >Algeria</option>
<option value="Zambia" >Zambia</option>
<option value="Zimbabwe" >Zimbabwe</option>
</select>

I am using select2 for this:

$(document).ready(function(){
$(".select2").select2();
});

And I also customized the way the select looks with this css:

.select2-container--default .select2-selection--single
{
    background-color: #21262d;
    border-color: #21262d;
    border-top-color: #21262d;
    border-right-color-value: #21262d;
    border-bottom-color: #21262d;
    border-left-color-value: #21262d;
    height: 34px;
}

It looks the way I want but I would like to change the color to white for the font of the selected item when user does that. How can I accomplish that?

http://jsfiddle.net/bhuffprL/

EDIT: Because not everyone seems to understand my goal - I want to change to white (fff) color ONLY WHEN user selects his/her own item from the list. The default option I want to be dark. In other words: 'Select a country' should be dark color as it is and when user selects a country from the list then I want to change font color to white.

I can think some of the solutions using JS though not sure if there's an easier way for that using the select2 plugin.

Easier way I can think of is to create a placeholder instead of having a default option.

From:

$(document).ready(function(){
  $(".select2").select2();
});

To:

$(document).ready(function(){
  $("#individual_taxCountry").select2({
    placeholder: "Select a state*"
  });
});

Then on your html, set an empty option value where the placeholder will take place.

Replacing this:

<option value="" selected="selected" class="selected">Select a country*</option>

To this:

<option></option> 

Then add those necessary css for the font color

.select2-container--default .select2-selection--single .select2-selection__placeholder {
  color: #444;
}

.select2-container--default .select2-selection--single .select2-selection__rendered {
    color: #fff;
}

Fiddle

Just add this css to your css code

.select2-container--default .select2-selection--single .select2-selection__rendered{
    color: #fff
}


https://jsfiddle.net/bhuffprL/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM