Home > front end >  Trigger different JavaScript functions on different selections in dropdown menu
Trigger different JavaScript functions on different selections in dropdown menu

Time:07-31

I have simple dropdown menu

<select name="dog-names" id="dog-names">
  <option value="rigatoni">Rigatoni</option>
  <option value="dave">Dave</option>
</select>

I want to trigger different JavaScript functions when each one of them are selected
for example I want to alert "Hello world" whenever Rigatoni is selected and I want to alert "I love you" whenever Dave is selected

function Hello() { 
alert("Hello world");
}

function Love() {
alert("I love you");
}

I know I could just pass the value to a function as a parameter and then use if/else but I have to avoid including conditional statements in my code.
is there any way to do this?

CodePudding user response:

// declare function dictionary
const fns = {
  rigatoni: Hello,
  dave: Love
}

function Hello() {
  alert("Hello world");
}

function Love() {
  alert("I love you");
}
// add event listener
const names = document.querySelector('#dog-names').addEventListener('change', ({target}) => {
  // run function based on value
  fns[target.value]()
})
<select name="dog-names" id="dog-names">
  <option value="rigatoni">Rigatoni</option>
  <option value="dave">Dave</option>
</select>

  • Related