Reputation: 129
I am learning JavaScript and I managed to change the background color:
<script>
function changecolor(id,color) {
id.style.backgroundColor=color;
}
</script>
<div id="container">
<p> Select Color to change background:</p>
<select id="themenu" onchange="changecolor(container,themenu.value)">
<option value="white"> </option>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="green">GREEN</option>
</select>
</div>
is there any other method to do it?
Upvotes: 2
Views: 581
Reputation: 1664
I just called the parent element and its working perfectly.
onchange="changecolor(this.parentNode,themenu.value)"
Upvotes: 3
Reputation: 15603
Your javascript function should be this;
function changecolor(id,color){
document.getElementById(id).style.backgroundColor=color;
}
Upvotes: 0
Reputation: 4833
You should simply refer to the current object (this), and then to it's parent node and it's value instead of using ids :
<script>
function useValueAsParentColor(menu) {
menu.parentNode.style.backgroundColor = menu.value;
}
</script>
<div>
<p> Select Color to change background:</p>
<select onchange="useValueAsParentColor(this); ">
<option value="white"> </option>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="green">GREEN</option>
</select>
</div>
Upvotes: 0
Reputation: 17366
You might just got stuck in the syntaxes
<select id="themenu" onchange="changecolor(container,this.value)"> <!-- Change -->
<option value="white"> </option>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="green">GREEN</option>
</select>
this.value
refers to the current object's selected value!
themenu.value
also works fine you might just got stuck somewhere else!
Upvotes: 4