Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trigger different JavaScript functions on different selections in dropdown menu

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

// 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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading