Execute various JavaScript functions based on selections made in a dropdown menu

I am working on a simple dropdown menu

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

My goal is to execute different JavaScript functions based on the option selected. For instance, I want to display an alert saying "Hello world" when Rigatoni is chosen and show "I love you" when Dave is picked.

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

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

I understand that I could pass the selected value as a parameter to a function and use if/else statements, but I am looking for a way to achieve this without using conditional statements in my code.
Is there any solution for this?

Answer №1

// Function dictionary declaration
const functions = {
  rigatoni: Greet,
  dave: Affectionate
}

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

function Affectionate() {
  alert("I love you");
}
// Event listener addition
const names = document.querySelector('#dog-names').addEventListener('change', ({target}) => {
  // Execute function based on selected value
  functions[target.value]()
})
<select name="dog-names" id="dog-names">
  <option value="rigatoni">Rigatoni</option>
  <option value="dave">Dave</option>
</select>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The situation where a Javascript switch case continues to fall through to the default case even when a 'break' statement

I am currently setting up a node.js discord bot that utilizes firebase to save a user's status. My switch statement is functioning smoothly, handling each command effectively. The default case looks like this: default: message.reply("Unknown comm ...

The JSX function seems to be malfunctioning, as the function part is not displaying on the webpage as intended

This code snippet is a part of a React component in a project. I have imported a CSS file for styling and have already integrated Material UI. However, the function for the new article is not displaying on the webpage as expected. import "./Widgets. ...

Find the position of an element in an array that includes a specific string value using JavaScript or Node.js

I need help figuring out how to find the index of an array that contains or includes a specific string value. Take a look at my code below to see what I've tried so far: Here is a simple example: var myarr = ["I", "like", "turtles"]; var arraycontai ...

Leveraging the .reduce method to perform specific calculations and generate an object containing the results of an array

After successfully achieving the desired results, here is the data manipulation I have done: const days = [ { date: '2016-12-13T00:00:00.000Z', stats: [ { name: 'Soft Drinks', sold: 34, }, { name: 'Snacks&apo ...

Is utilizing Promise.All more practical than async.each in this scenario?

Looking for a more efficient way to build an array instead of using async.each. Are there any alternative approaches in ES6 that I should consider? Would Promise.All be a better solution? async pushDataArray(response) { if (response && response.data & ...

Encountering issues when attempting to invoke a function from an external file in Angular4

When attempting to call a method from an external file using Angular4, I am encountering the following error: Error: ERROR in src/app/about/about.component.ts(22,9): error TS2304: Cannot find name 'checkJS'. Below is the code I am working with ...

What is the best way to target an iframe that includes "window.onclick" within its window?

Trying to integrate an HTML canvas game into my website poses a slight issue - the window requires a click on the iframe every time the page loads, which can be quite bothersome. I am looking for a way to automatically focus on the frame without manual int ...

Bundling and minifying Angular2 assets

In the world of ASP.NET (or gulp), bundling and minification are taken care of. However, a different issue arises when following Angular2 tutorials: the view HTML is typically embedded within the component itself. Fortunately, there is a way to separate th ...

The compatibility of Cross-Origin Requests with Socket.io in a Nginx + NodeJS setup is functioning incompletely

In my server system, I have an nginx and a nodejs server set up. Depending on the subdomain, requests are forwarded to the appropriate NodeJS app using proxy_pass. However, I am facing an issue when trying to use Socket.io from a different origin. The joi ...

Managing JSON responses in the client-side view technology of SpringMVC

I have been struggling to implement the following scenario using Spring MVC. I am encountering issues and unable to determine the correct approach. My implementation involves jsonRequest/jsonResponse (Restful Web services). 1. I have a SignUP.jsp Form wit ...

Issues with sending data using ajax

Trying to get weinre working through Ajax by calling this on dom ready: $.ajax({ url: 'http://debug.build.phonegap.com/target/target-script-min.js#hutber', dataType: "script", crossDomain: true, error: function(data){ c( ...

All nodes within the Angular ivh-treeview will automatically expand upon loading

Looking to optimize my AngularJS ivh-treeview. I am aiming to have all child nodes expanded without the need for manual expansion. Presently, the tree structure looks like this: $rootScope.nodes= [{ label: 'node1', value: &apo ...

Always keep the footer at the bottom of the viewport

I'm looking to display a footer with the user's name on my sidebar at the bottom of the viewport. I want it to act as a fixed bottom bar, always visible but only within the sidebar. To achieve this, I have created a function: function setFooter ...

Tips for updating specific properties of an object within a MongoDB database using arrays

I have encountered a problem with updating only specific properties of an object in my MongoDB database. While the query I'm using is working for most variables, it unexpectedly sets certain arrays (media: [] and sports: []) in the athleteProfile back ...

Steps to trigger a message box in SharePoint 2010

I have created a control with a RenderingTemplate for a customized ContentType that includes extra buttons. If one of the buttons in the code behind fails, I want to notify the user with a message box. Here is what I attempted: string script = "<scrip ...

Guide on how to receive multiple responses from a single ajax request in PHP

I am in the process of developing a web application that includes a search feature. When a user enters a name to search for, I use an AJAX request to retrieve and display records related to that specific person. However, due to the extensive amount of info ...

Ways to assign values to HTML table cells

I am facing an issue with two table cells where one span is located outside the td tag and the other is wrapped around td. <tr height="30"> <span data-name="toDD1" class="sstNumber"> </span> <td>Y</td> <span d ...

Best practices for avoiding string concatenation in Oracle-db with Node.js

Is there a way to prevent SQL injection caused by string concatenation in the SQL query? The searchParameter and searchString parameters, which come from a GET request, are optional. They should be added to the WHERE clause to filter results based on user ...

Guide on incorporating factories with Ionic/Angular JS while utilizing phonegap

I've been experimenting with global variables in my ionic/angular + phonegap app project by implementing a factory service. However, even adding a simple factory service like the one below somehow disrupts the app and causes all screens to turn compl ...

In a NextJS and Vite app, what is the recommended value for setting `jsx`?

To prevent encountering the following error ReferenceError: React is not defined ❯ Module.Home [as default] src/app/page.tsx:2:3 1| export default function Home() { 2| return <div>Home of Coach-Next</div>; | ^ 3| ...