Reputation: 682
Im using a dropdown taken from db, and showing
Size 2 - Out Of Stock Size 4 - Stock Size 5 - Out Of Stock
How can i add red color to out of stock text and green color on stock text via js?
My Dropdown:
<select name="super_attribute[<?php echo $_attribute->getAttributeId() ?>]" id="attribute<?php echo $_attribute->getAttributeId() ?>" class="required-entry super-attribute-select">
<option><?php echo $this->__('Choose an Option...') ?></option>
</select>
Upvotes: 0
Views: 35
Reputation: 42354
What you're asking is actually rather difficult to do. According to the HTML specification, the <option>
tag can only contain text. That means that you can't add a <span>
or something nice to only target the "In Stock" / "Out Of Stock" text.
Having said that, you can target the collection of <option>
elements themselves, and the easiest way to control the colours would be to assign each <option>
a class
while outputting them through PHP. Then you can target them with .getElementsByClassName()
, loop over them and style the text colour through .style.color
.
var in_stock = document.getElementsByClassName('in_stock');
var out_of_stock = document.getElementsByClassName('out_of_stock');
for (var i = 0; i < in_stock.length; i++) {
in_stock[i].style.color = 'green';
}
for (var i = 0; i < out_of_stock.length; i++) {
out_of_stock[i].style.color = 'red';
}
<select>
<option class="in_stock">Size 2 - In Stock</option>
<option class="out_of_stock">Size 5 - Out Of Stock</option>
</select>
Note that setting the colour for the <option>
elements does not set the default selection colour. For this, you'll want to target the <option>
tag directly, which can be done with .getElementsByTagName()
. You'll want to set the colour of this to the first <option>
by default, and the selected option when the selection changes:
var in_stock = document.getElementsByClassName('in_stock');
var out_of_stock = document.getElementsByClassName('out_of_stock');
for (var i = 0; i < in_stock.length; i++) {
in_stock[i].style.color = 'green';
}
for (var i = 0; i < out_of_stock.length; i++) {
out_of_stock[i].style.color = 'red';
}
/* Default <select> styling */
var the_select = document.getElementsByTagName('select')[0];
the_select.style.color = document.getElementsByTagName('option')[0].style.color;
/* Further <select> styling */
the_select.onchange = function() {
the_select.style.color = the_select.options[the_select.selectedIndex].style.color;
}
<select>
<option class="in_stock">Size 2 - In Stock</option>
<option class="out_of_stock">Size 5 - Out Of Stock</option>
</select>
Hope this helps!
Upvotes: 1