HTML form with more than one submit button and more than one action
15/04/2013I ruined almost all my evening just searching for the solution to having two submit buttons for an HTML form. The catch here was I wanted them to submit the form data to different scripts. After reading countless StackOverflow answers I came to the conclusion that there was no concrete solution to this, until of course I made use of jQuery. This being a very light weight project I did not want to introduce such heavy JS framework just for this simple task.
Well I must say, that I am very impressed with the simplicity and workability of the solution I wrote for myself and it is pretty straight forward. Here it goes
Sample Form:
| 1 2 3 4 5 6 | <form action="" method="post" id="myform"> <input type="text" name="val1"> <input type="text" name="val2"> <input type="button" value="Submit One" /> <input type="button" value="Submit Two" /> </form> |
The magical Javascript:
| 1 2 3 4 5 | function submitTo(what,to){ var frm=document.getElementById(what); frm.action = to; frm.submit(); } |
this is very easy to understand, it simply defines, what form needs to be submitted to what script. So lets say I need to submit a form with id “FormName1″ to a script called “ProcessForm.php” then we just need to call “submitTo(‘FormName1′,’ProcessForm.php’);”. Sounds easy, eh?
So the updated HTML becomes:
| 1 2 3 4 5 6 | <form action="" method="post" id="myform"> <input type="text" name="val1"> <input type="text" name="val2"> <input type="button" onClick="submitTo('myform','');" value="Submit One" /> <input type="button" onClick="submitTo('myform','some-script.php');" value="Submit Two" /> </form> |
As simple as that, the easiest solution out there, no complex javascript functions, no processing using php. There is also a method to read the button values from $_POST variables but that becomes useless, seeing the simplicity of this. Here is a quick fiddle for this, since the directory structure is not same at JSFiddle, this might not work entirely as expected, but will update soon!
Cheers!
Happy Hacking!






