javascripthtmlformsdomselectedindex

How to run a Java Script function if an HTML selector has a specific value?


So I have a very basic HTML form, and I'm trying to figure out how to run a JS function if a user selects a specific with a specific value, inside of an HTML element. I'm very, very new to coding so forgive me if it looks awful; But something like this, where say I want the background to turn red when an option with the value "two" is selected:

HTML:

<select id="numberDropdown">
  <option disabled selected>0</option>
  <option value="one">1</option>
  <option value="two">2</option>
  <option value="three">3</option>
</select> 

JavaScript:

   document.getElementById("numberDropdown").value = document.getElementById("numberDropdown").selectedIndex.value;
   if (document.getElementById("numberDropdown").value = "two"){
       document.body.style.backgroundColor = "red";
    };

I really don't know any java script, just tried to type something so you can understand the question. Thanks for any help!


Solution

  • This should get updated everytime a new value is selected

    const selectElement = document.getElementById("numberDropdown");
    
    selectElement.addEventListener('change', (event) => {
      let val = selectElement.options[selectElement.selectedIndex].value;
      if (val == "two"){
          document.body.style.backgroundColor = "red";
      }
    });