简体   繁体   English

HTML 表单,带有两个提交按钮和两个“目标”属性

[英]HTML form with two submit buttons and two "target" attributes

I have one HTML <form>.我有一个 HTML <form>。

The form has only one action="" attribute.该表单只有一个action=""属性。

However I wish to have two different target="" attributes, depending on which button you click to submit the form.但是,我希望有两个不同的target=""属性,具体取决于您单击哪个按钮来提交表单。 This is probably some fancy JavaScript code, but I haven't an idea where to begin.这可能是一些花哨的 JavaScript 代码,但我不知道从哪里开始。

How could I create two buttons, each submitting the same form, but each button gives the form a different target?如何创建两个按钮,每个按钮都提交相同的表单,但每个按钮都为表单提供不同的目标?

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 注意:我使用了GET,但它也适用于POST

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. 然后您可以轻松确定按下了哪个按钮 - 如果变量retry存在并且具有值,则按下重试,如果变量abort存在且具有值,则按下abort。 This knowledge can then be used to redirect to the appropriate place. 然后可以使用该知识将重定向到适当的位置。

This method needs no Javascript. 此方法不需要Javascript。

Note : that some browsers are capable of submitting a form without pressing any buttons (by pressing enter). 注意:某些浏览器无需按任何按钮即可提交表单(按Enter键)。 Non-standard as this is, you have to account for it, by having a clear default action and activating that whenever no buttons were pressed. 这是非标准的,您必须通过明确的default操作来解释它,并在没有按下任何按钮时激活它。 In other words, make sure your form does something sensible (whether that's displaying a helpful error message or assuming a default) when someone hits enter in a different form element instead of clicking a submit button, rather than just breaking. 换句话说,当有人点击输入不同的表单元素而不是单击提交按钮而不是仅仅打破时,请确保您的表单做了一些合理的事情 (无论是显示有用的错误消息还是假设默认值)。

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. 这里的不同之处在于,提交下的任何一个都是当用户通过按Enter提交表单时使用的那个,而另一个只有当用户明确点击按钮时才会触发。

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: 有了这个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. 将代码绑定到提交按钮的单击事件的方法将无法在IE上运行。

In case you are up to HTML5, you can just use the attribute formaction . 如果您符合HTML5,您可以使用属性formaction This allows you to have a different form action for each button. 这允许您为每个按钮设置不同的表单action

<!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>

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";' />

In this example, taken from 在这个例子中,取自

http://www.webdeveloper.com/forum/showthread.php?t=75170 http://www.webdeveloper.com/forum/showthread.php?t=75170

You can see the way to change the target on the button OnClick event. 您可以在按钮OnClick事件上看到更改目标的方法。

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');">

Example: 例:

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

Voila. 瞧。 Very "fancy", three word JavaScript! 非常“花哨”,三字JavaScript!

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 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");
}
?>

HTML: 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: JS:

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

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

<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>

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) {...}    


        }
    }); 

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>

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. 如果您不希望它们看到变量,也可以使用$ _SESSION来完成。

Alternate Solution. 替代解决方案。 Don't get messed up with onclick,buttons,server side and all.Just create a new form with different action like this. 不要搞砸onclick,按钮,服务器端和所有。只需创建一个具有不同动作的新表单。

<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() . 现在在Javascript中,您可以在getElementsByTagName()的帮助下获取v()中主窗体的所有元素。 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);
}   

This might help someone: 这可能会帮助某人:

Use the formtarget attribute 使用formtarget属性

<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>

e.submitEvent.originalEvent.submitter.value e.submitEvent.originalEvent.submitter.value

if you use event of form如果您使用表单事件

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; 然后有几个小js函数;

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


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

That should do the trick. 这应该够了吧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM