michael_builds_apps
michael_builds_apps

Reputation: 33

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!

Upvotes: 1

Views: 502

Answers (3)

curiousredoC
curiousredoC

Reputation: 51

You can wrap your javascript code in a function and use onchange attribute on the select tag. So whenever the select tag's value changes, your fuction will execute.

function changeColour() {
   let selectElement = document.getElementById("numberDropdown")
   let selectedValue = selectElement.options[selectElement.selectedIndex].value;
   if (selectedValue === "two"){
    document.body.style.backgroundColor = "red"
   }
 }

and you can change your html to

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

There are numerous ways to do it, as far as I know this is the simplest way.

Upvotes: 0

Ameya Rane
Ameya Rane

Reputation: 286

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";
  }
});

Upvotes: 1

sonEtLumiere
sonEtLumiere

Reputation: 4562

You can use a button to handle an event and get the value of the selected index of selector.

const btn = document.querySelector('#btn');
const selector = document.querySelector('#numberDropdown');

btn.onclick = (event) => {
event.preventDefault();
console.log(selector.selectedIndex)
    if (selector.selectedIndex == 2){
        document.body.style.backgroundColor = "red";
    }
};
<select id="numberDropdown">
  <option disabled selected>0</option>
  <option value="one">1</option>
  <option value="two">2</option>
  <option value="three">3</option>  
</select> 

<button id="btn">Get number</button>

Upvotes: 0

Related Questions