How to Specify Multiple Actions from Single Form Using Javascript?


In this programming tutorial we will learn how to specify multiple actions from single form using javascript. As we all know that there is always one submit button available in one form, so if you want to submit your form to multiple Web Pages then you have to use input buttons instead of submit button and javascript code for this purpose.
How to Specify Multiple Actions from Single Form Using Javascript?

Lets have a look over the example given below.
yourpage.php

<html>
<head>
<title>Specify Multiple Actions From Single Form</title>
<script language="javascript" type="text/javascript">
function FuncButton1()
{
document.form1.action = "Page1.php" //Sets the action attribute of the form
document.form1.submit(); // Submit the page
return true;
}

function FuncButton2()
{
document.form1.action = "Page2.php" //Sets the action attribute of the form
document.form1.submit(); // Submit the page
return true;
}

</script>
</head>

<body>
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<form name="form1" method="post">
<tr>
<td>First Name</td><td><input type="text" id="txt_Firstname" name="txt_Firstname"/></td>
</tr>
<tr>
<td>Last Name</td><td><input type="text" id="txt_Lastname" name="txt_Lastname"/></td>
</tr>
<tr>
<td>Email</td><td><input type="text" id="txt_Email" name="txt_Email"/></td>
</tr>
<tr>
<td>Username</td><td><input type="text" id="txt_Username" name="txt_Username"/></td>
</tr>
<tr>
<td><input type="button" value="Button1" onClick="return FuncButton1();" /></td><td><input type="button" value="Button2" onClick="return FuncButton2();"/></td>
</tr>
</form>
</tr>
</table>
</body>
</html>
Now lets understand.

First of all I have created a simple html form with two noticeable things. First noticeable thing is that there is no submit (type="submit") button in the form and secondly I have not set any action attribute of the form.

To post the data to two different web pages I have created two input buttons and using onClick event of these buttons I am setting the "action" of the form dynamically and then submit the form. So whenever user clicks the Button1 then the Page1.php will be called and whenever user clicks the Button2 then the Page2.php will be called.

So that's it. I love your feedback

0 comments: