Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Specifying multiple actions from a single Form

0.00/5 (No votes)
1 Aug 2000 1  
A simple way to send the data from a single form to different pages, depending on which 'submit' button the user chooses

Introduction

In writing the Self-posting scripts I needed a way to allow the user to send their HTML to either the next page for processing, or to a preview page so they could check first. Basically I wanted 2 "submit" buttons on a single form, but there seemed no obvious way to do it. After asking around and (gasp!) reading the docs I came across a simple method that I hope will save someone else half a day of messing around.

The Problem

Say I have a form such as below:

Screenshot - form.png

We want Button1 to send the data to one page, and Button2 to send it to a completely different page. Your <form> tag specifies the action to take when the submit button is pressed - but we can only specify a single action.

A Solution

One way to get around this is to handle each button's OnClick event and set the "action" for the form dynamically:

<!-- create the form -->
<form name="Form1" method="post">

<!-- Add the data entry bits -->
Your Name <input type="text" name="text1" size="10" /><br />

<!-- Add some buttons -->
<INPUT type="button" value="Button1" name=button1 onclick="return OnButton1();">
<INPUT type="button" value="Button2" name=button2 onclick="return OnButton2();">

<!-- close the form -->
</form>

Our button click handlers for Button1 and Button2 would look like the following:

<script language="Javascript">
<!--
function OnButton1()
{
    document.Form1.action = "Page1.aspx"
    document.Form1.target = "_blank";    // Open in a new window

    document.Form1.submit();             // Submit the page

    return true;
}

function OnButton2()
{
    document.Form1.action = "Page2.aspx"
    document.Form1.target = "_blank";    // Open in a new window

    document.Form1.submit();             // Submit the page

    return true;
}
-->
</script>
<noscript>You need Javascript enabled for this to work</noscript>

Where Page1.aspx should be called when Button1 is pressed, and Page2.aspx called when Button2 is pressed.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here