1 submit button but 2 actions to be performed based on the selection from dropdown in javascript

I need to have one submit button but it needs to perform 2 different actions based on the value selected from the dropdown.

The dropdown has values "Order","Search","Alerts".

When I select Order and then submit it should redirect the way it is i.e, submitForm () should trigger.

When I select Search and then submit it should redirect to a different return URL or return Form.

. How should I returnForm or the return URL in javascript? How do I differentiate between the click.?

The file is completely a HTML and js file


Solution 1:

You can use an event listener on the form element to listen for submit event of the form, then every time the form is submitted you can get the current value of the select element and use an if/else if statement or even a switch case (in this example I'm using if and else if statement) to call tasks based on the select element's value.

HTML:

<form>
    <select name="dropdown" id="dropdown">
        <option value="order">Order</option>
        <option value="search">Search</option>
        <option value="alerts">Alerts</option>
    </select>
    <button type="submit">submit</button>
</form>

JAVASCRIPT:

const form = document.querySelector("form");
const selectElement = form.querySelector("#dropdown");

form.addEventListener("submit", (event) => {

  event.preventDefault();

  if (selectElement.value === "order") {

    // Do stuff for order
    console.log("Completed tasks for order");

  } else if (selectElement.value === "search") {

    // Do stuff for search
    console.log("Completed tasks for search");

  } else if (selectElement.value === "alerts") {

    // Do stuff for alerts
    console.log("Completed tasks for alerts");

  } else {

    console.log("Do nothing");

  }
});