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 badges2 Answers
Reset to default 5You 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.