Skip to content Skip to sidebar Skip to footer

Set Selected Option Via Css?

Is it possible to set the selected attribute of an option tag via a CSS class? I'm wondering if something like the following is possible in a stylesheet: option.selected { select

Solution 1:

Nope, CSS only alters the presentation, not the content (although CSS3 does support some modification of content, but not the selection of values.) You'll need to use JavaScript if you can't modify the HTML directly.

Solution 2:

Not via CSS, but it can be accomplished via javascript.

functionsetSelects() {

    var allSelects = document.getElementsByTagName("select");
    for (var i = 0; i < allSelects.length; i++) {
        for (var j = 0; j < allSelects[i].options.length; j++) {
            if (allSelects[i].options[j].className == "selected") {

                allSelects[i].selectedIndex = j;
            }
        }
    }
}

window.onload = setSelects;

As other people have pointed out, I'm not sure why you'd want to do it via a CSS class in the first place.

Solution 3:

option[selected] {background-color:skyblue;color:white;}

in case you want to show the previous marked selection - independend of the changes from the user after displaying a result, the old selected remain sykblue, the new changes are in darkblue.

Solution 4:

If you use JQuery then you can do something very much along those lines, but not CSS on its own.

Solution 5:

Yes it is possible, but I am not sure about IE

Below code will change style for default selected item.

<style>
           option[selected="selected"] {
           color:red;
           font-weight:bold
           }
           </style><select><optionvalue="1">Txt</option><optionvalue="2"selected="selected">Another Txt</option></select>

Post a Comment for "Set Selected Option Via Css?"