Home > Software engineering >  change background color with select options and submit button JS/HTML
change background color with select options and submit button JS/HTML

Time:10-18

I have a element in my HTML file. Once the user selects an option and then clicks the submit button. I want the entire webpage background color (including elements with IDs) to change.

function ChangeBackground()
    {
        
      var optionselected = document.querySelector("#option1").value;
      var optionselected = document.querySelector("*").style = "background-color:red;";
      
    }
<p><b><u>customize the background color!</b></u></p>
<label for="Colors"> Select a Color:</label>
<select id="Colors">
    <option id="option1" style="background-color:red;">Red</option>
    <option id="option2" style="background-color:green;">Green</option>
    <option id="option3" style="background-color:blue;">Blue</option>
</select>
<br><br>
<button onclick="ChangeBackground();">Submit Change</button>

CodePudding user response:

const changeBackground = () => {
  document.body.style.backgroundColor = document.getElementById('colors').value;
}
<p><b><u>Input information below to customize the background color!</b></u>
</p>
<label for="colors"> Select a Color:</label>
<select id="colors">
  <option id="option1" style="background-color:red;">Red</option>
  <option id="option2" style="background-color:green;">Green</option>
  <option id="option3" style="background-color:blue;">Blue</option>
</select>
<br><br>
<button onclick="changeBackground();">Submit Change</button>

CodePudding user response:

document.querySelector("*") selects only first element so you should use document.querySelectorAll("*") instead and change the styles for each element.

function ChangeBackground() {
    var optionselected = document.querySelector("select").value;
    document
        .querySelectorAll("*")
        .forEach((el) => (el.style.backgroundColor = optionselected));
}
<p><b><u>Input information below to customize the background color!</u></b>
</p>
<label for="Colors"> Select a Color:</label>
<select id="Colors">
    <option id="option1" style="background-color: red">Red</option>
    <option id="option2" style="background-color: green">Green</option>
    <option id="option3" style="background-color: blue">Blue</option>
</select>
<br /><br />
<button onclick="ChangeBackground();">Submit Change</button>

  • Related