...
HTML, Tutorials

How to have one form with multiple actions

01 January 2019

The easiest way to dynamically change the form action when clicking each button (of type button, not submit which is the default), and then submit the form.

HTML Form

In the Form tag, here we have taken 3 buttons for 3 different actions for one form. You can also take different buttons as per your requirement.

<form id="myform" name="myform" method="post" action="">
  <input id="myinput" name="myinput" type="text"/> 
  <button type="button" onClick="deleteAction()">DELETE</button>
  <button type="button" onClick="updateAction()">UPDATE</button>
  <button type="button" onClick="saveAction()">SAVE</button>
</form>

Javascript

In javascript, here we have 3 different functions for 3 different button action. then we have taken a common function changeActionAndSubmit() for setting form’s action dynamically.

function deleteAction() {
    changeActionAndSubmit('/action/delete');
}

function updateAction() {
    changeActionAndSubmit('/action/update');
}

function saveAction() {
    changeActionAndSubmit('/action/save');
}

function changeActionAndSubmit(action) {
    document.getElementById('myform').action = action;
    document.getElementById('myform').submit();
}

Summary:

javascript makes easier to implement functionality of having one HTML form with multiple actions.

Leave a Comments