Skip to content Skip to sidebar Skip to footer

How To Change The Background Color Of A Div From A Dropdown Menu?

Is it possible to change the background color of a DIV based on the end-user's selection from a drop down list? For example, I have a drop down menu with options for blue, green,

Solution 1:

document.getElementById("PreviewResults").style.background-color= BackgroundValue;

This doesn’t work, because what you have here would a subtraction operation in JavaScript, because - is the operator for that.

To access any style properties that contain - you need to either remove the - and replace the following letter with its uppercase version:

document.getElementById("PreviewResults").style.backgroundColor = BackgroundValue;

or use the square bracket syntax:

document.getElementById("PreviewResults").style["background-color"] = BackgroundValue;

Solution 2:

Make sure you are using style.backgroundColor to actually set your background :

document.getElementById("PreviewResults").style.background-color= BackgroundValue;

You also may want to consider setting the value of your default option to transparent (the initial value for the background) so that the user could switch back after a change was made :

<selectid=selector><optionvalue="transparent">Select Background</option><optionvalue="blue">Blue</option><optionvalue="yellow">Yellow</option><optionvalue="green">Green</option><optionvalue="red">Red</option></select>

You can see an example of this in action here and demonstrated below :

enter image description here

Solution 3:

Change the line

document.getElementById("PreviewResults").style.background-color= BackgroundValue;

to

document.getElementById("PreviewResults").style.backgroundColor = BackgroundValue;

Post a Comment for "How To Change The Background Color Of A Div From A Dropdown Menu?"