bsegraves
bsegraves

Reputation: 1020

How to style the disabled and selected 'option' of a 'select' in HTML5

I'm trying to use the first 'option' of a 'select' tag as a prompt to the user that input is required. So, I'd like the 'select' box to render the selection in a different color if the selected option is disabled.

So given the following code:

<select>
  <option selected="selected" disabled="disabled">Choose best player...</option>
  <option>Walter Payton</option>
  <option>Jim McMahon</option>
  <option>Mike Singletary</option>
  <option>Richard Dent</option>
  <option>Steve McMichael</option>
  <option>Wilber Marshall</option>
</select>

I'd like the page to show the dropdown with "Choose best player..." in the color gray and then change the color if a non-disabled option is chosen.

I'd prefer a css solution if it exists, but after googling for quite some time I'm beginning to be convinced that some JavaScript will be required. Any simple solutions out there?

Here's a codepen with this preloaded.

Upvotes: 1

Views: 2449

Answers (3)

Jon P
Jon P

Reputation: 19797

Pure css you want:

select option[disabled="disabled"][selected="selected"]
{text-decoration:underline;}

This will style an option with both disabled and selected set. However, beware of browser compatability issues.

Demo

It won't however remove the style when another option is selected. According to MDN option:checked should be able to be used, but I have not been able to get it to work reliably (http://jsfiddle.net/gb35e6yj/).

Upvotes: 0

Tim Jensen
Tim Jensen

Reputation: 3

I think your difficulty (with a pure css solution) will be targeting your select element based on the attributes of a child element.

I would use some javascript to check that selected item isn't disabled and then apply your css.

Upvotes: 0

dashtinejad
dashtinejad

Reputation: 6263

I think you need a little javascript:

HTML

<select onchange="highlight(this)">
    <option class="invalid" selected="selected" disabled="disabled">Choose best player...</option>
    <option>Walter Payton</option>
    <option>Jim McMahon</option>
    <option>Mike Singletary</option>
    <option>Richard Dent</option>
    <option>Steve McMichael</option>
    <option>Wilber Marshall</option>
</select>

CSS

option.invalid {
    background: #eee;
}

option.valid {
    background: #ff8;
}

JavaScript

function highlight(field){
    field.options[0].className = 'valid';
}

jsFiddle Demo.

Upvotes: 1

Related Questions