简体   繁体   中英

Style Option in Selectbox using Javascript

I need your help.

I am dynamically adding options to a select box using the code below. However, how can I add a style each option in the select box using javascript? and doing it dynamically?

var status = new Array()
status[0] = ""
status[1] = "ACTIVE"
status[2] = "ON HOLD"
status[3] = "CLOSED"
for (i=0; i<status.length; i++) { document.getElementById('status').options[i]=new Option(status[i], i) }

ie.) [DROP DOWN MENU] ACTIVE (text color is green) ON HOLD (text color is yellow) CLOSED (text color is red)

Thanks for all your help and support.

Cheers,

Jay

You can style each element independently, or you can set up css classes before hand and just assign the classname to the element.

See this stackoverflow question: Style Option in Selectbox using Javascript

Check out this fiddle: http://jsfiddle.net/xdXFz/

Optionally, see how to dynamically create select with options :

Sample:

var status = ["", "ACTIVE", "ON HOLD", "CLOSED"];
var select = document.getElementById("status");

for ( var i = 0; i < status.length; i++ ){

    var option = document.createElement("option");
        // ex: Assign a css class to the option
        option.setAttribute('class', 'Your_CSS_Classname_Here');

        // ex: style the option inline
        option.style.fontWeight = 'bold';

        // set the value of the option
        option.setAttribute("value", status[i]);

        // set the text that displays for the option
        option.innerHTML = status[i];

    // add the option to your select dropdown
    select.appendChild(option);

}

Maybe something like this:

var status = new Array()
status[0] = ""
status[1] = "ACTIVE" 
status[2] = "ON HOLD" 
status[3] = "CLOSED"

var s1 = status[1];
var s2 = status[2];
var s3 = status[3];

if (s1) {
  //style here
}
else if (s2) {
  //style here
}
else if (s3) {
  //style here
}

for (i=0; i<status.length; i++) { document.getElementById('status').options[i]=new Option(status[i], i) } 

Not anywhere near tested or refined.

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