fmc
fmc

Reputation: 490

Is there a way to keep a selected select box option colored?

All I'm tying to do is keep the color of the selected option so it appears in the select box.

<div class="controls col-sm-2">
  <select class="form-control">
    <option>SELECT</option>
    <option style="color:red;background:red">RED</option>
    <option style="color:blue;background:blue">BLUE</option>
    <option style="color:gold;background:gold">GOLD</option>
    <option style="color:orange;background:orange">ORANGE</option>
    <option style="color:green;background:green">GREEN</option>
  </select>
</div>

The colored bars show up in the dropdown but are are lost when selected to the select box. Is there a way to keep the colors for display in the select box? This isn't mission critical or anything, but I thought there might be a way to keep the styling.

Upvotes: 0

Views: 1834

Answers (2)

Conan
Conan

Reputation: 2709

Possible (although not strictly recommended ;) with some tweaks to both the markup:

<div class="controls col-sm-2">
  <select class="form-control">
    <option value="">SELECT</option>
    <option value="red">RED</option>
    <option value="blue">BLUE</option>
    <option value="gold">GOLD</option>
    <option value="orange">ORANGE</option>
    <option value="green">GREEN</option>
  </select>
</div>

... and the CSS:

select, option {
  background-color: #fff;
}

select.red,
option[value='red'] { background-color: red; }

select.blue,
option[value='blue'] { background-color: blue; }

select.gold,
option[value='gold'] { background-color: gold; }

select.orange,
option[value='orange'] { background-color: orange; }

select.green,
option[value='green'] { background-color: green; }

Unfortunately to get the behaviour you're after, you'll also need a smattering of JavaScript (jQuery flavour follows):

// every time we change the selection in the dropdown ...
$('select').on('change', function() {
    $(this)
        // clear any previous selection defined in the class
        .attr('class', 'form-control')
        // now add the selected value as an additional class (which we can target via CSS)
        .addClass($(this).children(':selected').val());
});

Note that this will affect each and every <select> element on the page, so you may want to target the colour dropdown variant with (say) a specific class, e.g. select.colour-dropdown.

Demo available on http://www.bootply.com/ppZL9u1FAO.

Upvotes: 1

nncho
nncho

Reputation: 165

I may have an answer for your specific case, using jQuery:

$(".form-control").change(function(){

$(this).css("background-color", $(this).val());

});

Upvotes: 1

Related Questions