-2

I'm trying to change my header to a different color based on what is chosen from the drop box options. I am using JS to update the color, but it is not changing.

function changeStyle() {
  var element = document.getElementById("changestyle");
  element.style.color = "#FF0000";
}
#changestyle {
  border: 1px solid #CCC;
  width: 100px;
  height: 100px;
}
<h1>Customize the Page</h1>
<form>
  <p>Pick the color
    <select id="TextColor" onchange="changestyle(color)">
      <option value="r">Red</option>
      <option value="g">Green</option>
      <option value="p">Purple</option>
    </select>
  </p>
  <input type="button" value="Update" onclick="header.style.changecolor">
Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • There's alot going on here. Rather than address it all, what element exactly do you want to change, when do you want the change to happen (on select or on click) and I assume you want it to become whatever is selected in the select menu – Kinglish Nov 29 '22 at 03:23
  • `changestyle` and `header` don’t exist. `header.style.changecolor` does nothing, even if `header` existed. Inline event handlers like `onclick` are [bad practice](/q/11737873/4642212). They’re an [obsolete, cumbersome, and unintuitive](/a/43459991/4642212) way to listen for events. Always [use `addEventListener`](//developer.mozilla.org/en/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. Use the [browser console (dev tools)](//webmasters.stackexchange.com/q/8525) (hit `F12`), read any errors. – Sebastian Simon Nov 29 '22 at 03:26

1 Answers1

0

There are several bugs in your code,

The correct code is below:

function changeStyle(color) {
  var element = document.getElementById("header");
  element.style.color = color;
}

document.querySelector('#btn').addEventListener('click', () => {
    changeStyle(TextColor.value)
})
#changestyle {
  border: 1px solid #CCC;
  width: 100px;
  height: 100px;
}
<h1 id="header">Customize the Page</h1>
<form>
  <p>Pick the color
    <select id="TextColor">
      <option value="red">Red</option>
      <option value="green">Green</option>
      <option value="purple">Purple</option>
    </select>
  </p>
  <input type="button" value="Update" id="btn">
</form>
  
lv_
  • 198
  • 1
  • 8