最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Style Option in Selectbox using Javascript - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked Oct 11, 2012 at 16:20 Jason KellyJason Kelly 2,65510 gold badges45 silver badges82 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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

Check out this fiddle, make sure to select option 2 in the dropdown: http://jsfiddle/xdXFz/

Optionally, see how to dynamically create select with options:

Sample:

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

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

    var elOption = document.createElement("option");
        // ex: Assign a css class to the option
        elOption.setAttribute('class', 'Your_CSS_Classname_Here');
        
        // ex: style the option
        elOption.style.fontWeight = 'bold';
        
        // set the value of the option
        elOption.setAttribute("value", statuses[i]);
        
        // set the text that displays for the option
        elOption.innerHTML = statuses[i];
    
    // add the option to your select dropdown
    elSelect.appendChild(elOption);

}

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.

发布评论

评论列表(0)

  1. 暂无评论