change form action with select option via onchange Function() using Javascript

Change Form Action with Select Option via onchange Function() using JavaScript

If you have a website with a form that requires different actions depending on the user's selection, you can use JavaScript to dynamically change the form's action attribute. This is useful when you have multiple forms on the same page with different actions or when you want to change the action based on user input.

Step 1: Create the HTML Form

First, create an HTML form with a select element that contains the different options for the form action:

<form id="myForm">
  <select id="actionSelect" onchange="changeAction()">
    <option value="https://example.com/action1">Action 1</option>
    <option value="https://example.com/action2">Action 2</option>
    <option value="https://example.com/action3">Action 3</option>
  </select>
  <input type="submit" value="Submit">
</form>

Note that we have added an ID to the form element (myForm) and the select element (actionSelect), as well as an onchange attribute to the select element that calls the changeAction() function.

Step 2: Create the JavaScript Function

Next, create a JavaScript function that will be called when the user selects a different option:

<script>
  function changeAction() {
    var form = document.getElementById("myForm");
    var select = document.getElementById("actionSelect");
    var action = select.value;
    form.action = action;
  }
</script>

This function gets the form and select elements by their IDs, gets the selected value of the select element, and sets the form's action attribute to that value. Notice that the function is called onchange of the select element.

Step 3: Test the Form

Now you can test the form by selecting different options from the select element and submitting the form. The form action will change dynamically based on your selection.

Alternative Method: Using Event Listeners

Instead of using the onchange attribute in the HTML, you can use JavaScript to add an event listener to the select element:

<script>
  var select = document.getElementById("actionSelect");
  select.addEventListener("change", changeAction);
</script>

This code adds an event listener to the select element that calls the changeAction() function when the user selects a different option. This method may be easier to maintain if you have multiple forms or if you want to separate your HTML and JavaScript code.

Overall, using JavaScript to dynamically change a form's action attribute can be a useful technique for creating more flexible and dynamic forms on your website.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe