19

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!

posfan12
  • 2,541
  • 8
  • 35
  • 57

3 Answers3

31

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>
zylstra
  • 740
  • 1
  • 8
  • 22
13

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');
  });
});
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • Can I combine the POST and GET methods? For instance, I want to pass a URL containing fields but also the form elements by their names. – posfan12 May 02 '10 at 11:44
  • 1
    @posfan12 - You can only submit via one method at a time, though you could serialize and post to a url with params. I'm not following you on why you would ever need to have both though, it's more data for the client to send as well and generally not a great idea. – Nick Craver May 02 '10 at 11:48
  • You can have both POST and GET at the same time. When you add parameters to the url with '?' and '&' they will become the GET and if you have also POST parameters defined they will be in the POST at the same request. – Johan Van de Merwe Jul 22 '20 at 07:03
1

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>
Peter O.
  • 32,158
  • 14
  • 82
  • 96