1

I have tried a lot but can not do this. I want to show the red background colour to the selectbox after option is selected.

<select>
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

<style type="text/css">
select:hover { 
    background:#Ff0000; 
    color : #ffffff;
}
</style>
nanobash
  • 5,419
  • 7
  • 38
  • 56
Atif Azad
  • 697
  • 2
  • 9
  • 21

4 Answers4

3

Try this:

var select = document.getElementById('mySelect');
select.onchange = function () {
    select.className = 'redText';
}
.redText {
    background-color:#F00;
}
<select id="mySelect">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>
doppelgreener
  • 4,809
  • 10
  • 46
  • 63
  • 1
    @HashirAzad this can be improve by calling the function in HTML. like [this](http://jsfiddle.net/venkateshwar/LgD7w/1/). – Mr_Green Mar 20 '14 at 10:33
  • The suggestion of Mr_Green - divami.com actually works and is CSS only whilst the options below don't work (using html5, Mac Safari and/or Chrome) - highly reccomended! – Jeremy Young Sep 04 '17 at 14:05
0

You need to use javascript/jquery to handle change selection event for selectbox and add red background

rt2800
  • 3,045
  • 2
  • 19
  • 26
0

HTML

<select>
    <option>Select</option>
    <option selected>im selected</option>
    <option>im not</option>
    <option>me too</option>
    <option>me either</option>
</select>

CSS

select { color: black; background: red; }
option:not(:checked) { background: white; }

http://jsfiddle.net/kQ6c5/

EDIT

http://www.w3.org/TR/selectors/#checked:

the :checked pseudo-class initially applies to such elements that have the HTML4 selected and checked attributes

Vincent Panugaling
  • 896
  • 1
  • 12
  • 28
0

Absolutely yes, you can do this using :checked selector,

Check this demo jsFiddle

Syntax

option:checked { }

HTML

<select>
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

CSS

option:checked { 
    background:#Ff0000; 
    color : #ffffff;
}
Jaykumar Patel
  • 26,836
  • 12
  • 74
  • 76