Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different form ACTION depending on button pressed

I have a form and I would like the ACTION field to be different depending on the button pressed.

For instance the form might get processed by different PHP files if I press button A or button B.

How can I do this?

Thanks!

like image 823
posfan12 Avatar asked May 02 '10 11:05

posfan12


People also ask

Can a form have multiple actions?

Let's learn the steps of performing multiple actions with multiple buttons in a single HTML form: Create a form with method 'post' and set the value of the action attribute to a default URL where you want to send the form data. Create the input fields inside the as per your concern. Create a button with type submit.

Can a HTML form have 2 submit buttons?

yes, multiple submit buttons can include in the html form. One simple example is given below.

What is action and method in form?

The method attribute specifies how to send form-data (the form-data is sent to the page specified in the action attribute). The form-data can be sent as URL variables (with method="get" ) or as HTTP post transaction (with method="post" ). Notes on GET: Appends form-data into the URL in name/value pairs.


3 Answers

If you don't want to use Javascript, but do use HTML5, you can use the attribute formaction:

<!DOCTYPE html>
<html>
  <body>
    <form>
      <input type="submit" formaction="http://firsttarget.com" value="Submit to first" />
      <input type="submit" formaction="http://secondtarget.com" value="Submit to second" />
    </form>
  </body>
</html>
like image 52
zylstra Avatar answered Oct 13 '22 17:10

zylstra


In your buttons you can just set the form's action, using it's form property, for example on button a:

this.form.action = "fileA.php";

On the other:

this.form.action = "fileB.php";

You can rig this up externally, like this:

document.getElementById("buttonA").onclick = function() { 
  document.getElementById("myForm").action = "fileA.php";
};

Or if you're using a library like jQuery:

$(function() {
  $("#buttonA").click(function() {
    $(this).closest("form").attr('action', 'fileA.php');
  });
});
like image 30
Nick Craver Avatar answered Oct 13 '22 15:10

Nick Craver


Leave the action field blank:

<form action ="" method="post" name="form1">
<input type ="submit" onclick="calA();"/>
<input type = "submit" onclick="calB"/>
</form>

<script>
function calA()
{
 document.form1.action ="a.php";
}
function calB()
{
document.form1.action = "b.php";
}
</script>
like image 1
citydarshan Avatar answered Oct 13 '22 17:10

citydarshan