I have a form selector element, which has an inline script following onchange:
<select onchange="this.className=this.options[this.selectedIndex].className">
<option value="select">Select color</option>
<option class="greenOpt" value="green" >Green</option>
<option class="yellowOpt" value="yellow" >Yellow</option>
<option class="blueOpt" value="blue" >Blue</option>
</select>
This works perfectly for my output, changing the background color of the options the same color as their word, Green is green, Yellow is yellow, etc.
.greenOpt{
background-color: green;
text-shadow: -1px 0 white, 0 1px white, 1px 0 white, 0 -1px white;
}
.blueOpt{
background-color: blue;
text-shadow: -1px 0 white, 0 1px white, 1px 0 white, 0 -1px white;
}
.yellowOpt{
background-color: yellow;
text-shadow: -1px 0 white, 0 1px white, 1px 0 white, 0 -1px white;
}
But I want to move that onchange
script into an external function and I am unsure of how that should look. I understand what I need to do in the <select>
tag, is onchange="colorSel()"
My function so far:
function colorSel() {
var colors = document.getElementById("colors");
colors = this.className = this.options[this.selectedIndex].className;
}
I am stumped. I have changed the parameter the of the function and the getElement type to many different things. I just don't get it.
You have not provided the code for the colors element, so I have demonstrated something with what you have given:
change = function(selectObject) {
selectObject.className= selectObject.options[selectObject.selectedIndex].className
}
.greenSel{
background-color: green;
text-shadow: -1px 0 white, 0 1px white, 1px 0 white, 0 -1px white;
}
.blueSel{
background-color: blue;
text-shadow: -1px 0 white, 0 1px white, 1px 0 white, 0 -1px white;
}
.yellowSel{
background-color: yellow;
text-shadow: -1px 0 white, 0 1px white, 1px 0 white, 0 -1px white;
}
<select onchange="change(this)">
<option value="select">Select color</option>
<option class="greenSel" value="green" >Green</option>
<option class="yellowSel" value="yellow" >Yellow</option>
<option class="blueSel" value="blue" >Blue</option>
</select>
You missed passing in this to your onchange method and grabbing the value from the selected choice.