I’m going to show you how to use two submit buttons in a Form using JavaScript. It’s not so hard as you think.
First start with a Normal HTML form with two buttons:
1 2 3 4 5 6 7 |
<form action="" method="post" name="myform"> <!-- This is normal submit button submits the form --> <input type="submit" value="Actual Submit Button" /> <!-- This button again going to submit the form but you can have any other operation before submitting the form --> <input type="button" onclick="submitForm();" id="btn_submit" value="Normal Button Going to act as a Submit Button" /> </form> |
If you see the above form, I had put two buttons one is “type=submit” button and other one is normal “type=button”. But, in the normal button there is a function added onClick ie., (onclick=”submitForm()”)
Now, lets see the JavaScript:
1 2 3 4 5 6 |
//this function will submit the form function submitForm(){ //myform is the form name ie.,name="myform" alert('Instead of this (alert) you can write any other function! - After you press OK "Form will be submitted" '); myform.submit(); } |
So, when the normal button is clicked, submitForm() function will be called and inside the function first we are going to display an alert and then submit the form.
Why to display an alert?
Just to show you the difference which button is clicked and also you can do other functionality before submitting the form.
Here is the entire code, so you can play with that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<html> <head> <title>Two Submit buttons in a HTML form using JavaScript</title> <script> //this function will submit the form function submitForm(){ //myform is the form name ie.,name="myform" alert('Instead of this (alert) you can write any other function! - After you press OK "Form will be submitted" '); myform.submit(); } </script> </head> <body> <form action="" method="post" name="myform"> <!-- This is normal submit button submits the form --> <input type="submit" value="Actual Submit Button" /> <!-- This button again going to submit the form but you can have any other operation before submitting the form --> <input type="button" onclick="submitForm();" id="btn_submit" value="Normal Button Going to act as a Submit Button" /> </form> </body> </html> |
Also, see the demo here 🙂