...

View Full Version : Using JS to changing the background color in a drop down.



IndyNS
05-30-2012, 02:11 AM
Here is what I am trying to do. I am using a JS button to create a new row in a table. In the new row I have two text boxes and a drop down list. I am wanting to set the background color of each of my options in the drop list.

Here is the section of the JS code that I create the drop down list.
//cell 1
var cell1 = row.insertCell(1);
var el = document.createElement("select");
el.name = 'Status[]' // sets the name of the row to status
el.options[0] = new Option("Available");
el.options[1] = new Option("Busy");

cell1.appendChild(el);

In my HTML code I can get the first drop down list to have color but for any additional rows the color is not set. Any thoughts or suggestions would be greatly appreciated. I have been hitting my head against a wall for two weeks now.

Old Pedant
05-30-2012, 02:18 AM
You just need to set in on each option.

If you want them to all have the same color, you could do it with CSS.

Also, you really should give both value and text for the options.


var cell1 = row.insertCell(1);
var el = document.createElement("select");
el.name = 'Status[]' // sets the name of the row to status
el.className = "...your choice of class name..."; // optional
el.options[0] = new Option("Available","Available");
el.options[0].style.color = "red"; // optional
el.options[1] = new Option("Busy","Busy");
el.options[1].style.color = "blue"; // optional
cell1.appendChild(el);

If you choose to do it via the classname on the <select>, then just add to your <style>:


<style type="text.css">
select.YourChoice option {
color: red;
}
</style>

Note that MSIE only supports color and backgroundColor as styles you can change on a per-option basis. (Might not be true for MSIE 9.)

Old Pedant
05-30-2012, 02:23 AM
Interesting!

Firefox IGNORES a style request for the option until you click on the <select>.

An easy fix:


<style>
select.YourClassName, select.YourClassName option { color: red; background-color: yellow; font-style: italic; }
</style>

Now all options, at all times, will show that color and background color.

But yes, even MSIE 9 (and I know MSIE 8 and7) ignores the italic request unless it is placed on the <select>. It ignores it on individual <option>s.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum