HTML form with two submit buttons and two "target" attributes
Asked Answered
F

16

79

I have one HTML <form>.

The form has only one action="" attribute.

However I wish to have two different target="" attributes, depending on which button you click to submit the form. This is probably some fancy JavaScript code, but I haven't an idea where to begin.

How could I create two buttons, each submitting the same form, but each button gives the form a different target?

Frankel answered 3/6, 2009 at 2:13 Comment(3)
There's a usability issue here: What happens when I hit 'enter' instead of clicking a button? You're going to have to cancel the submit event of the form, most likely.Tennyson
The form should have one button that is the 'default' if the form is submitted but none of the buttons were activated. The default should be chosen wisely. Note that the 'hit enter' thing is a browser-specific extension only and shouldn't be relied upon, whereas all browsers are capable of activating a specific button.Opportunist
Possible duplicate of Two submit buttons in one formHannie
O
64

It is more appropriate to approach this problem with the mentality that a form will have a default action tied to one submit button, and then an alternative action bound to a plain button. The difference here is that whichever one goes under the submit will be the one used when a user submits the form by pressing enter, while the other one will only be fired when a user explicitly clicks on the button.

Anyhow, with that in mind, this should do it:

<form id='myform' action='jquery.php' method='GET'>
    <input type='submit' id='btn1' value='Normal Submit'>
    <input type='button' id='btn2' value='New Window'>
</form>

With this javascript:

var form = document.getElementById('myform');
form.onsubmit = function() {
    form.target = '_self';
};

document.getElementById('btn2').onclick = function() {
    form.target = '_blank';
    form.submit();
}

Approaches that bind code to the submit button's click event will not work on IE.

Oligopoly answered 3/6, 2009 at 2:37 Comment(1)
Since HTML5, it is possible to use <input type="submit" formaction="action2.php" value="Other Action"></input>Chorea
O
79

Update 2015:

This question and answer was from so many years ago when "wanting to avoid relying on Javascript" was more of a thing than it is today. Today I would not consider writing extra server-side functionality for something like this. Indeed, I think that in most instances where I would need to submit form data to more than one target, I'd probably be doing something that justified doing a lot of the logic client-side in Javascript and using XMLHttpRequest (or indeed, the Fetch API) instead.

Update 2023:

I would definitely be writing a lot of logic in the front end Javascript code and would be using the Fetch API these days.

Original answer follows:


I do this on the server-side. That is, the form always submits to the same target, but I've got a server-side script who is responsible for redirecting to the appropriate location depending on what button was pressed.

If you have multiple buttons, such as

<form action="mypage" method="get">

  <input type="submit" name="retry" value="Retry" />
  <input type="submit" name="abort" value="Abort" />

</form>

Note: I used GET, but it works for POST too

Then you can easily determine which button was pressed - if the variable retry exists and has a value then retry was pressed, and if the variable abort exists and has a value then abort was pressed. This knowledge can then be used to redirect to the appropriate place.

This method needs no Javascript.

Opportunist answered 3/6, 2009 at 3:3 Comment(5)
I'm not sure if it's because 7 years have passed since this answer but this method does not work for me (Testing in Chrome)Vesta
This should work as it did 7 years ago. You just shouldn't need to worry about the note at the bottom anymore.Opportunist
How does redirecting to the appropriate location work for POST too? Assumming that location is a url I'd think all data is gone... I must be overlooking something or someone'd have mentioned that in the last 7 years... Is that what @Vesta means?Ejectment
The redirect after a post would not pass on any additional form data to the target URL. In the trivial example I gave that's not an issue because there are no other form elements. If you have other form data you would need to pass it on to the destination in some other way, for example by translating it to a query string, or passing it out of band. The typical scenario for this type of thing, for me, was to have one "submit" action and one "cancel" action (or a "go here instead" action") and only the latter action redirected. Which is another way to do it without worrying about POST data.Opportunist
action = location. action ≠ target. See w3schools.com/tags/att_a_target.asp .Boldt
O
64

It is more appropriate to approach this problem with the mentality that a form will have a default action tied to one submit button, and then an alternative action bound to a plain button. The difference here is that whichever one goes under the submit will be the one used when a user submits the form by pressing enter, while the other one will only be fired when a user explicitly clicks on the button.

Anyhow, with that in mind, this should do it:

<form id='myform' action='jquery.php' method='GET'>
    <input type='submit' id='btn1' value='Normal Submit'>
    <input type='button' id='btn2' value='New Window'>
</form>

With this javascript:

var form = document.getElementById('myform');
form.onsubmit = function() {
    form.target = '_self';
};

document.getElementById('btn2').onclick = function() {
    form.target = '_blank';
    form.submit();
}

Approaches that bind code to the submit button's click event will not work on IE.

Oligopoly answered 3/6, 2009 at 2:37 Comment(1)
Since HTML5, it is possible to use <input type="submit" formaction="action2.php" value="Other Action"></input>Chorea
A
56

In case you are up to HTML5, you can just use the attribute formaction. This allows you to have a different form action for each button.

<!DOCTYPE html>
<html>
  <body>
    <form>
      <input type="submit" formaction="firsttarget.php" value="Submit to first" />
      <input type="submit" formaction="secondtarget.php" value="Submit to second" />
    </form>
  </body>
</html>
Alienage answered 27/3, 2012 at 17:18 Comment(3)
Good one. You can catch the click event via jQuery and change the forms action attribute to make this compatible with older browsers.Aperient
formaction ≠ target. formaction is the location (i.e. URL) that the form is submitted to. target is the name of the browser tab/window that the form results are displayed on.Boldt
Hot! Hot! Hot! However did I miss this when I revised for html5?Wallaroo
S
8

This works for me:

<input type='submit' name='self' value='This window' onclick='this.form.target="_self";' />

<input type='submit' name='blank' value='New window' onclick='this.form.target="_blank";' />
Shortly answered 1/10, 2013 at 14:2 Comment(0)
B
7

In this example, you can see the way to change the target on the button OnClick event.

function subm(f,newtarget)
{
document.myform.target = newtarget ;
f.submit();
}

<FORM name="myform" method="post" action="" target="" >

<INPUT type="button" name="Submit" value="Submit" onclick="subm(this.form,'_self');">
<INPUT type="button" name="Submit" value="Submit" onclick="subm(this.form,'_blank');">
Bernardina answered 3/6, 2009 at 2:22 Comment(0)
E
3

Simple and easy to understand, this will send the name of the button that has been clicked, then will branch off to do whatever you want. This can reduce the need for two targets. Less pages...!

<form action="twosubmits.php" medthod ="post">
<input type = "text" name="text1">

<input type="submit"  name="scheduled" value="Schedule Emails">
<input type="submit"  name="single" value="Email Now">
</form>

twosubmits.php

<?php
if (empty($_POST['scheduled'])) {
// do whatever or collect values needed
die("You pressed single");
}

if (empty($_POST['single'])) {
// do whatever or collect values needed
die("you pressed scheduled");
}
?>
Estimate answered 4/11, 2013 at 15:42 Comment(0)
A
2

Example:

<input 
  type="submit" 
  onclick="this.form.action='new_target.php?do=alternative_submit'" 
  value="Alternative Save"
/>

Voila. Very "fancy", three word JavaScript!

Anthelion answered 12/6, 2013 at 7:21 Comment(2)
Does this permanently change the form action or just for that one click?Laurencelaurene
@Laurencelaurene onclick works every time you click on it however normally a submit would reload the page or take you to a new page when you click on it.Anthelion
T
1

Here's a quick example script that displays a form that changes the target type:

<script type="text/javascript">
    function myTarget(form) {
        for (i = 0; i < form.target_type.length; i++) {
            if (form.target_type[i].checked)
                val = form.target_type[i].value;
        }
        form.target = val;
        return true;
    }
</script>
<form action="" onSubmit="return myTarget(this);">
    <input type="radio" name="target_type" value="_self" checked /> Self <br/>
    <input type="radio" name="target_type" value="_blank" /> Blank <br/>
    <input type="submit">
</form>
Tellurian answered 3/6, 2009 at 2:34 Comment(0)
G
1

HTML:

<form method="get">
<input type="text" name="id" value="123"/>
<input type="submit" name="action" value="add"/>
<input type="submit" name="action" value="delete"/>
</form>

JS:

$('form').submit(function(ev){ 
ev.preventDefault();
console.log('clicked',ev.originalEvent,ev.originalEvent.explicitOriginalTarget) 
})

http://jsfiddle.net/arzo/unhc3/

Gustaf answered 21/8, 2013 at 13:28 Comment(1)
explicitOriginalTarget is a mozilla specific extensionLeash
J
1
<form id='myForm'>
    <input type="button" name="first_btn" id="first_btn">
    <input type="button" name="second_btn" id="second_btn">
</form>

<script>

$('#first_btn').click(function(){
    var form = document.getElementById("myForm")
    form.action = "https://foo.com";
    form.submit();
});

$('#second_btn').click(function(){
    var form = document.getElementById("myForm")
    form.action = "http://bar.com";
    form.submit();
});

</script>
Jaddo answered 15/5, 2015 at 2:18 Comment(0)
P
1

It is do-able on the server side.

<button type="submit" name="signin" value="email_signin" action="/signin">Sign In</button>
<button type="submit" name="signin" value="facebook_signin"  action="/facebook_login">Facebook</button>

and in my node server side script

app.post('/', function(req, res) {
if(req.body.signin == "email_signin"){
            function(email_login) {...} 
        }
if(req.body.signin == "fb_signin"){
            function(fb_login) {...}    


        }
    }); 
Precast answered 28/4, 2016 at 11:6 Comment(0)
W
0

On each of your buttons you could have the following;

<input type="button" name="newWin" onclick="frmSubmitSameWin();">
<input type="button" name="SameWin" onclick="frmSubmitNewWin();">

Then have a few small js functions;

<script type="text/javascript">
    function frmSubmitSameWin() {
        form.target = '';
        form.submit();
    }


    function frmSubmitNewWin() {
        form.target = '_blank';
        form.submit();
    }
</script>

That should do the trick.

Wolfsbane answered 3/6, 2009 at 2:27 Comment(0)
K
0

Have both buttons submit to the current page and then add this code at the top:

<?php
    if(isset($_GET['firstButtonName'])
        header("Location: first-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
    if(isset($_GET['secondButtonName'])
        header("Location: second-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
?>

It could also be done using $_SESSION if you don't want them to see the variables.

Kegler answered 24/11, 2009 at 17:46 Comment(0)
P
0

Alternate Solution. Don't get messed up with onclick,buttons,server side and all.Just create a new form with different action like this.

<form method=post name=main onsubmit="return validate()" action="scale_test.html">
<input type=checkbox value="AC Hi-Side Pressure">AC Hi-Side Pressure<br>
<input type=checkbox value="Engine_Speed">Engine Speed<br>
<input type=submit value="Linear Scale" />
</form>
<form method=post name=main1 onsubmit="return v()" action=scale_log.html>
<input type=submit name=log id=log value="Log Scale">
</form>

Now in Javascript you can get all the elements of main form in v() with the help of getElementsByTagName(). To know whether the checkbox is checked or not

function v(){
var check = document.getElementsByTagName("input");

    for (var i=0; i < check.length; i++) {
        if (check[i].type == 'checkbox') {
            if (check[i].checked == true) {

        x[i]=check[i].value
            }
        }
    }
console.log(x);
}   
Petrina answered 11/2, 2014 at 4:35 Comment(0)
E
0

This might help someone:

Use the formtarget attribute

<html>
  <body>
    <form>
      <!--submit on a new window-->
      <input type="submit" formatarget="_blank" value="Submit to first" />
      <!--submit on the same window-->
      <input type="submit" formaction="_self" value="Submit to second" />
    </form>
  </body>
</html>
Eleanore answered 11/2, 2018 at 18:59 Comment(0)
P
0

e.submitEvent.originalEvent.submitter.value

if you use event of form

Perfect answered 25/2, 2022 at 7:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.