如何确定HTML表单上的默认提交按钮?

时间:2022-11-24 10:28:47

If a form is submitted but not by any specific button, such as

如果表单是提交的,但不是通过任何特定的按钮,比如。

  • by pressing Enter
  • 按输入
  • using HTMLFormElement.submit() in JS
  • 在JS使用HTMLFormElement.submit()

how is a browser supposed to determine which of multiple submit buttons, if any, to use as the one pressed?

浏览器如何确定在多个提交按钮(如果有的话)中使用哪个按钮?

This is significant on two levels:

这在两个层面上是重要的:

  • calling an onclick event handler attached to a submit button
  • 调用附加到提交按钮的onclick事件处理程序
  • the data sent back to the web server
  • 发送回web服务器的数据

My experiments so far have shown that:

到目前为止,我的实验表明:

  • when pressing Enter, Firefox, Opera and Safari use the first submit button in the form
  • 当按下Enter键时,Firefox、Opera和Safari使用表单中的第一个submit按钮。
  • when pressing Enter, IE uses either the first submit button or none at all depending on conditions I haven't been able to figure out
  • 按Enter时,IE会使用第一个submit按钮,或者完全不使用,这取决于我无法确定的条件
  • all these browsers use none at all for a JS submit
  • 所有这些浏览器都不使用任何JS提交

What does the standard say?

标准是怎么说的?

If it would help, here's my test code (the PHP is relevant only to my method of testing, not to my question itself)

如果有帮助,这里是我的测试代码(PHP只与我的测试方法相关,而与我的问题本身无关)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>

<body>

<h1>Get</h1>
<dl>
<?php foreach ($_GET as $k => $v) echo "<dt>$k</dt><dd>$v</dd>"; ?>
</dl>

<h1>Post</h1>
<dl>
<?php foreach ($_POST as $k => $v) echo "<dt>$k</dt><dd>$v</dd>"; ?>
</dl>

<form name="theForm" method="<?php echo isset($_GET['method']) ? $_GET['method'] : 'get'; ?>" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>">
    <input type="text" name="method" />
    <input type="submit" name="action" value="Button 1" onclick="alert('Button 1'); return true" />
    <input type="text" name="stuff" />
    <input type="submit" name="action" value="Button 2" onclick="alert('Button 2'); return true" />
    <input type="button" value="submit" onclick="document.theForm.submit();" />
</form>

</body></html>

14 个解决方案

#1


101  

If you submit the form via Javascript (i.e. formElement.submit() or anything equivalent), then none of the submit buttons are considered successful and none of their values are included in the submitted data. (Note that if you submit the form by using submitElement.click() then the submit that you had a reference to is considered active; this doesn't really fall under the remit of your question since here the submit button is unambiguous but I thought I'd include it for people who read the first part and wonder how to make a submit button successful via JS form submission. Of course, the form's onsubmit handlers will still fire this way whereas they wouldn't via form.submit() so that's another kettle of fish...)

如果您通过Javascript提交表单(即formElement.submit()或任何类似的内容),那么提交的所有按钮都不会被认为是成功的,它们的值也没有包含在提交的数据中。(请注意,如果您使用submitElement.click()提交表单,则您引用的提交被认为是活动的;这并不属于你的问题范围,因为这里的submit按钮是明确的,但是我想我应该把它包含在那些读过第一部分并且想知道如何通过JS表单提交成功提交一个submit按钮的人。当然,表单的onsubmit处理程序仍将以这种方式触发,而它们不会通过form.submit(),因此这是另一个问题……

If the form is submitted by hitting Enter while in a non-textarea field, then it's actually down to the user agent to decide what it wants here. The specs don't say anything about submitting a form using the enter key while in a text entry field (if you tab to a button and activate it using space or whatever, then there's no problem as that specific submit button is unambiguously used). All it says is that a form must be submitted when a submit button is activated, it's not even a requirement that hitting enter in e.g. a text input will submit the form.

如果表单是通过在非textarea字段中单击Enter提交的,那么实际上是由用户代理决定它在这里想要什么。规范中没有提到在文本输入字段中使用enter键提交表单(如果您对按钮进行标签并使用空格或其他方式激活表单,那么毫无疑问,会使用特定的submit按钮)。它的意思是,当一个提交按钮被激活时,必须提交一个表单,甚至不需要点击enter,例如,文本输入将提交表单。

I believe that Internet Explorer chooses the submit button that appears first in the source; I have a feeling that Firefox and Opera choose the button with the lowest tabindex, falling back to the first defined if nothing else is defined. There's also some complications regarding whether the submits have a non-default value attribute IIRC.

我认为Internet Explorer选择了源文件中最先出现的submit按钮;我有一种感觉,Firefox和Opera选择的按钮的tabindex是最低的,如果没有其他的定义,就会回到第一个定义的按钮。对于提交是否具有非默认值属性IIRC,也存在一些复杂的问题。

The point to take away is that there is no defined standard for what happens here and it's entirely at the whim of the browser - so as far as possible in whatever you're doing, try to avoid relying on any particular behaviour. If you really must know, you can probably find out the behaviour of the various browser versions but when I investigated this a while back there were some quite convoluted conditions (which of course are subject to change with new browser versions) and I'd advise you to avoid it if possible!

需要注意的一点是,这里没有定义标准,它完全是浏览器的心血来潮——因此,无论你在做什么,尽量避免依赖于任何特定的行为。如果你真的必须知道,你可能会发现不同的浏览器版本的行为但是当我调查这一段时间,有一些相当复杂的情况(当然如有更改,恕新版本的浏览器),我建议你尽可能避免它!

#2


55  

Andrezj's pretty much got it nailed... but here's an easy cross-browser solution.

Andrezj已经搞定了……但这里有一个简单的跨浏览器解决方案。

Take a form like this:

采取这样的形式:

<form>
    <input/>
    <button type="submit" value="some non-default action"/>
    <button type="submit" value="another non-default action"/>
    <button type="submit" value="yet another non-default action"/>

    <button type="submit" value="default action"/>
</form>

and refactor to this:

和重构:

<form>
    <input/>

    <button style="overflow: visible !important; height: 0 !important; width: 0 !important; margin: 0 !important; border: 0 !important; padding: 0 !important; display: block !important;" type="submit" value="default action"/>

    <button type="submit" value="some non-default action"/>
    <button type="submit" value="another non-default action"/>
    <button type="submit" value="yet another non-default action"/>
    <button type="submit" value="still another non-default action"/>

    <button type="submit" value="default action"/>
</form>

Since the W3C spec indicates multiple submit buttons are valid, but omits guidance as to how the user-agent should handle them, the browser manufacturers are left to implement as they see fit. I've found they'll either submit the first submit button in the form, or submit the next submit button after the form field that currently has focus.

由于W3C规范指出多个提交按钮是有效的,但是省略了用户代理应该如何处理它们的指导,浏览器制造商可以根据自己的需要来实现它们。我发现他们要么在表单中提交第一个提交按钮,要么在当前有焦点的表单字段之后提交下一个提交按钮。

Unfortunately, simply adding a style of display: none; won't work because the W3C spec indicates any hidden element should be excluded from user interactions. So hide it in plain sight instead!

不幸的是,只需添加一种显示样式:none;无法工作,因为W3C规范指出任何隐藏的元素都应该被排除在用户交互之外。所以,把它藏在显眼的地方吧!

Above is an example of the solution I ended up putting into production. Hitting the enter key triggers the default form submission is behavior as expected, even when other non-default values are present and precede the default submit button in the DOM. Bonus for mouse/keyboard interaction with explicit user inputs while avoiding javascript handlers.

上面是我最终投入生产的解决方案的一个例子。按下enter键会触发默认表单提交,这是预期的行为,即使在DOM中出现其他非默认值并先于默认提交按钮时也是如此。使用显式用户输入进行鼠标/键盘交互,同时避免使用javascript处理程序。

Note: tabbing through the form will not display focus for any visual element yet will still cause the invisible button to be selected. To avoid this issue, simply set tabindex attributes accordingly and omit a tabindex attribute on the invisible submit button. While it may seem out of place to promote these styles to !important, they should prevent any framework or existing button styles from interfering with this fix. Also, those inline styles are definitely poor form, but we're proving concepts here... not writing production code.

注意:通过表单制表将不会显示任何可视元素的焦点,但仍然会导致选择不可见按钮。为了避免这个问题,只需相应地设置tabindex属性,并在不可见的submit按钮上省略一个tabindex属性。虽然它看起来不适合推广这些样式,但是它们应该阻止任何框架或现有的按钮样式来干扰这个修复。而且,这些内联样式确实很糟糕,但是我们在这里证明了一些概念……不写产品代码。

#3


50  

HTML 4 does not make it explicit. The current HTML5 working draft specifies that the first submit button must be the default:

HTML 4并没有明确说明它。当前的HTML5工作草案规定,第一个提交按钮必须是默认的:

A form element's default button is the first submit button in tree order whose form owner is that form element.

表单元素的默认按钮是树中的第一个提交按钮,其表单所有者是该表单元素。

If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.

如果用户代理支持让用户隐式提交表单(例如,在一些平台上按下“输入”键集中隐式提交表单文本框时),那么这样做的一种默认按钮定义了激活行为必须导致用户代理运行合成默认按钮的点击激活步骤。

#4


16  

I think this post would help if someone wants to do it with jQuery:

如果有人想用jQuery,我觉得这篇文章会有所帮助:

http://greatwebguy.com/programming/dom/default-html-button-submit-on-enter-with-jquery/

http://greatwebguy.com/programming/dom/default-html-button-submit-on-enter-with-jquery/

The basic solution is:

基本的解决方案是:

$(function() {
    $("form input").keypress(function (e) {
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
        $('input[type=submit].default').click();
        return false;
    } else {
        return true;
    }
    });
});

and another I liked was:

另一个我喜欢的是:

jQuery(document).ready(function() {
$("form input, form select").live('keypress', function (e) {
if ($(this).parents('form').find('button[type=submit].default, input[type=submit].default').length <= 0)
return true;

if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$(this).parents('form').find('button[type=submit].default, input[type=submit].default').click();
return false;
} else {
return true;
}
});
}); 

#5


6  

I had a form with 11 submit buttons on it, and it would always use the first submit button when the user pressed enter. I read elsewhere that it is not a good idea (bad practice) to have more than one submit button on a form, and the best way to do this is have the button you want as default, as the only submit button on the form. The other buttons should be made into "TYPE=BUTTON" and an onClick event added that calls your own submit routine in Javascript. Something like this :-

我有一个包含11个提交按钮的表单,当用户按下enter时,它总是使用第一个提交按钮。我在别处读到过,在表单上有多个提交按钮不是一个好主意(不好的实践),最好的方法是将您想要的按钮作为默认设置,作为表单上惟一的提交按钮。其他按钮应该被设置为“TYPE=BUTTON”,并添加一个onClick事件,该事件在Javascript中调用您自己的提交例程。这样的:-

<SCRIPT Language="JavaScript">
function validform()
{
  // do whatever you need to validate the form, and return true or false accordingly
}

function mjsubmit()
{
  if (validform()) { document.form1.submit(); return true;}
  return false;
}
</SCRIPT>
<INPUT TYPE=BUTTON NAME="button1" VALUE="button1" onClick="document.form1.submitvalue='button1'; return mjsubmit();">
<INPUT TYPE=BUTTON NAME="button2" VALUE="button2" onClick="document.form1.submitvalue='button2'; return mjsubmit();">
<INPUT TYPE=SUBMIT NAME="button3" VALUE="button3" onClick="document.form1.submitvalue='button3'; return validform();">
<INPUT TYPE=BUTTON NAME="button4" VALUE="button4" onClick="document.form1.submitvalue='button4'; return mjsubmit();">

Here, button3 is the default, and although you are programmatically submitting the form with the other buttons, the mjsubmit routine validates them. HTH.

在这里,button3是默认值,尽管您正在用其他按钮以编程方式提交表单,但是mjsubmit例程会验证它们。HTH。

#6


4  

This can now be solved using flexbox:

现在可以用flexbox解决这个问题:

HTML

HTML

<form>
    <h1>My Form</h1>
    <label for="text">Input:</label>
    <input type="text" name="text" id="text"/>

    <!-- Put the elements in reverse order -->
    <div class="form-actions">
        <button>Ok</button> <!-- our default action is first -->
        <button>Cancel</button>
    </div>
</form>

CSS

CSS

.form-actions {
    display: flex;
    flex-direction: row-reverse; /* reverse the elements inside */
}

Explaination
Using flex box, we can reverse the order of the elements in a container that uses display: flex by also using the CSS rule: flex-direction: row-reverse. This requires no CSS or hidden elements. For older browsers that do not support flexbox, they still get a workable solution but the elements will not be reversed.

通过使用flex box进行解释,我们可以通过使用CSS规则:flex-direction: row-reverse来逆转使用display: flex的容器中的元素的顺序。这不需要CSS或隐藏元素。对于不支持flexbox的旧浏览器,他们仍然可以得到一个可行的解决方案,但是元素不会被逆转。

Demo
http://codepen.io/Godwin/pen/rLVKjm

演示http://codepen.io/Godwin/pen/rLVKjm

#7


2  

I struggled with the same question since i had submit button in the middle of the from which redirected submit to another page, like so:

由于我在重定向提交到另一个页面的中间有一个submit按钮,所以我一直在思考同样的问题,如下所示:

<button type="submit" onclick="this.form.action = '#another_page'">More</button>

When user pressed enter key, this button was clicked instead of another submit button.

当用户按下enter键时,这个按钮被点击而不是另一个提交按钮。

So i did some primitive tests by creating a from with multiple submit buttons and different visibility options and onclick event alerting which button was clicked: https://jsfiddle.net/aqfy51om/1/

所以我做了一些原始的测试,通过创建一个包含多个提交按钮和不同可见性选项的from,以及onclick事件提醒按钮被单击:https://jsfiddle.net/aqfy51om/1/

Browsers and OS'es i used for testing:

我用于测试的浏览器和操作系统:

WINDOWS

窗户

  • Google Chrome 43 (c'mon google :D)
  • 谷歌Chrome 43(来吧谷歌:D)
  • Mozilla Firefox 38
  • Mozilla Firefox 38
  • Internet Explorer 11
  • Internet Explorer 11
  • Opera 30.0
  • Opera 30.0

OSX

OSX

  • Google Chrome 43
  • Google Chrome 43
  • Safari 7.1.6
  • Safari 7.1.6

Most of these browsers clicked very first button despite the visibility options applied exept IE and Safari which clicked the third button, which is "visible" inside "hidden" container:

大多数浏览器都点击了第一个按钮,尽管应用了exept IE和Safari,点击了第三个按钮,在“隐藏”容器中是“可见的”:

<div style="width: 0; height: 0; overflow: hidden;">
    <button type="submit" class="btn btn-default" onclick="alert('Hidden submit button #3 was clicked');">Hidden submit button #3</button>
</div>

So my suggestion, which i'm going to use myself, is:

所以我的建议,我将会用到我自己,是:

If you form has multiple submit buttons with different meaning, then include submit button with default action at the beginning of the form which is either:

如果您的表单有多个不同含义的提交按钮,则在表单的开头包含带有默认动作的提交按钮,即:

  1. Fully visible
  2. 完全可见
  3. Wrapped in a container with style="width: 0; height: 0; overflow: hidden;"
  4. 用样式="宽度:0 "的容器包装;高度:0;溢出:隐藏。”

EDIT Another option might be to offset the button(still at the beginning of the from) style="position: absolute; left: -9999px; top: -9999px;", just tried it in IE - worked , but i have no idea what else it can screw up, for example printing..

编辑另一个选项可能是偏移按钮(仍然在from开头)style="position: absolute;左:-9999 px;前:-9999像素;",刚在IE下试过,但我不知道它还能搞砸什么,比如打印……

#8


1  

From your comments:

从你的评论:

A consequence is that, if you have multiple forms submitting to the same script, you can't rely on submit buttons to distinguish them.

结果是,如果有多个表单提交给同一个脚本,就不能依靠提交按钮来区分它们。

I drop an <input type="hidden" value="form_name" /> into each form.

我将放入每个表单。

If submitting with javascript: add submit events to forms, not click events to their buttons. Saavy users don't touch their mouse very often.

如果使用javascript提交:将提交事件添加到表单,而不是单击事件到它们的按钮。Saavy用户不经常触摸他们的鼠标。

#9


1  

When you have multiple submit buttons in a single form and a user presses the ENTER key to submit the form from a text field, this code overrides default functionality, by calling the submit event on the form from the key press event. Here is that code:

当您在一个表单中有多个提交按钮,并且用户按ENTER键从文本字段提交表单时,此代码通过从键按事件调用表单上的submit事件来覆盖默认功能。是代码:

$('form input').keypress(function(e){

    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)){ $(e.target).closest('form').submit(); return false; }
    else return true;

});

#10


1  

Strange that the first button Enter goes always to the first button regardless is visible or not, e.g. using jquery show/hide(). Adding attribute .attr('disabled', 'disabled') prevent receiving Enter submit button completely. It's problem for example when adjusting Insert/Edit+Delete button visibility in record dialogs. I found less hackish and simple placing Edit in front of Insert

奇怪的是,第一个按钮输入总是指向第一个按钮,不管它是否可见,例如使用jquery show/hide()。添加属性.attr('disabled', 'disabled')可完全阻止接收Enter submit按钮。例如,在记录对话框中调整插入/编辑+删除按钮的可见性是一个问题。我发现在插入前放置编辑器不那么容易

<button type="submit" name="action" value="update">Update</button>
<button type="submit" name="action" value="insert">Insert</button>
<button type="submit" name="action" value="delete">Delete</button>

and use javascript code:

并使用javascript代码:

$("#formId button[type='submit'][name='action'][value!='insert']").hide().attr('disabled', 'disabled');
$("#formId button[type='submit'][name='action'][value='insert']").show().removeAttr('disabled');

#11


0  

my recipe:

我的食谱:

<form>
<input type=hidden name=action value=login><!-- the magic! -->

<input type=text name=email>
<input type=text name=password>

<input type=submit name=action value=login>
<input type=submit name=action value="forgot password">
</form>

It will send the default hidden field if none of the buttons are 'clicked'.

如果没有一个按钮是“单击”的,它将发送默认的隐藏字段。

if they are clicked, they have preference and it's value is passed.

如果它们被单击,它们有首选项,并传递它的值。

#12


0  

Another solution I've used is to just have one button in the form, and fake the other buttons.

我使用的另一种解决方案是在表单中只有一个按钮,然后伪造其他按钮。

Here's an example:

这里有一个例子:

<form>
  <label for="amount">Amount of items</label>
  <input id="amount" type="text" name="amount" />
  <span id="checkStock" class="buttonish">Check stock</span>
  <button type="submit" name="action" value="order">Place order</button>
</form>

I then style the span elements to look like a button. A JS listener observes the span and performs the desired operation once clicked.

然后将span元素样式化为一个按钮。JS侦听器会观察跨度,并在单击后执行所需的操作。

Not necessarily right for all situations, but at least it's pretty easy to do.

不一定适用于所有情况,但至少很容易做到。

#13


0  

From the HTML 4 spec:

来自HTML 4规范:

If a form contains more than one submit button, only the activated submit button is successful.

如果表单包含多个submit按钮,则只有激活的submit按钮是成功的。

This means that given more than 1 submit button and none activated (clicked), none should be successful.

这意味着,如果提交按钮超过1个,且没有激活(单击),则不应该成功。

And I'd argue this makes sense: Imagine a huge form with multiple submit-buttons. At the top, there is a "delete this record"-button, then lots of inputs follow and at the bottom there is an "update this record"-button. A user hitting enter while in a field at the bottom of the form would never suspect that he implicitly hits the "delete this record" from the top.

我认为这是有道理的:想象一个有多个提交按钮的巨大表单。在顶部,有一个“删除这个记录”按钮,然后大量的输入跟随,在底部有一个“更新这个记录”按钮。当用户在表单底部的字段中点击进入时,绝不会怀疑他从顶部隐去了“删除这条记录”。

Therefore I think it is not a good idea to use the first or any other button it the user does not define (click) one. Nevertheless, browsers are doing it of course.

因此,我认为使用用户没有定义(单击)的第一个或其他按钮不是一个好主意。不过,浏览器当然会这么做。

#14


-2  

EDIT: Sorry, when writing this answer I was thinking about submit buttons in the general sense. The answer below is not about multiple type="submit" buttons, as it leaves only one type="submit" and change the other to type="button". I leave the answer here as reference in case helps someone that can change the type in their form:

编辑:对不起,当我写这个答案的时候,我在考虑一般意义上的提交按钮。下面的答案不是关于多个type="submit"按钮,因为它只留下一个type="submit",而将另一个改为type="button"。我把答案留在这里作为参考,以防有人可以改变他们的形式:

To determine what button is pressed when hitting enter, you can mark it up with type="submit", and the other buttons mark them with type="button". For example:

要确定按enter时按了哪个按钮,可以用type="submit"标记它,其他按钮用type="button"标记它们。例如:

<input type="button" value="Cancel" />
<input type="submit" value="Submit" />

#1


101  

If you submit the form via Javascript (i.e. formElement.submit() or anything equivalent), then none of the submit buttons are considered successful and none of their values are included in the submitted data. (Note that if you submit the form by using submitElement.click() then the submit that you had a reference to is considered active; this doesn't really fall under the remit of your question since here the submit button is unambiguous but I thought I'd include it for people who read the first part and wonder how to make a submit button successful via JS form submission. Of course, the form's onsubmit handlers will still fire this way whereas they wouldn't via form.submit() so that's another kettle of fish...)

如果您通过Javascript提交表单(即formElement.submit()或任何类似的内容),那么提交的所有按钮都不会被认为是成功的,它们的值也没有包含在提交的数据中。(请注意,如果您使用submitElement.click()提交表单,则您引用的提交被认为是活动的;这并不属于你的问题范围,因为这里的submit按钮是明确的,但是我想我应该把它包含在那些读过第一部分并且想知道如何通过JS表单提交成功提交一个submit按钮的人。当然,表单的onsubmit处理程序仍将以这种方式触发,而它们不会通过form.submit(),因此这是另一个问题……

If the form is submitted by hitting Enter while in a non-textarea field, then it's actually down to the user agent to decide what it wants here. The specs don't say anything about submitting a form using the enter key while in a text entry field (if you tab to a button and activate it using space or whatever, then there's no problem as that specific submit button is unambiguously used). All it says is that a form must be submitted when a submit button is activated, it's not even a requirement that hitting enter in e.g. a text input will submit the form.

如果表单是通过在非textarea字段中单击Enter提交的,那么实际上是由用户代理决定它在这里想要什么。规范中没有提到在文本输入字段中使用enter键提交表单(如果您对按钮进行标签并使用空格或其他方式激活表单,那么毫无疑问,会使用特定的submit按钮)。它的意思是,当一个提交按钮被激活时,必须提交一个表单,甚至不需要点击enter,例如,文本输入将提交表单。

I believe that Internet Explorer chooses the submit button that appears first in the source; I have a feeling that Firefox and Opera choose the button with the lowest tabindex, falling back to the first defined if nothing else is defined. There's also some complications regarding whether the submits have a non-default value attribute IIRC.

我认为Internet Explorer选择了源文件中最先出现的submit按钮;我有一种感觉,Firefox和Opera选择的按钮的tabindex是最低的,如果没有其他的定义,就会回到第一个定义的按钮。对于提交是否具有非默认值属性IIRC,也存在一些复杂的问题。

The point to take away is that there is no defined standard for what happens here and it's entirely at the whim of the browser - so as far as possible in whatever you're doing, try to avoid relying on any particular behaviour. If you really must know, you can probably find out the behaviour of the various browser versions but when I investigated this a while back there were some quite convoluted conditions (which of course are subject to change with new browser versions) and I'd advise you to avoid it if possible!

需要注意的一点是,这里没有定义标准,它完全是浏览器的心血来潮——因此,无论你在做什么,尽量避免依赖于任何特定的行为。如果你真的必须知道,你可能会发现不同的浏览器版本的行为但是当我调查这一段时间,有一些相当复杂的情况(当然如有更改,恕新版本的浏览器),我建议你尽可能避免它!

#2


55  

Andrezj's pretty much got it nailed... but here's an easy cross-browser solution.

Andrezj已经搞定了……但这里有一个简单的跨浏览器解决方案。

Take a form like this:

采取这样的形式:

<form>
    <input/>
    <button type="submit" value="some non-default action"/>
    <button type="submit" value="another non-default action"/>
    <button type="submit" value="yet another non-default action"/>

    <button type="submit" value="default action"/>
</form>

and refactor to this:

和重构:

<form>
    <input/>

    <button style="overflow: visible !important; height: 0 !important; width: 0 !important; margin: 0 !important; border: 0 !important; padding: 0 !important; display: block !important;" type="submit" value="default action"/>

    <button type="submit" value="some non-default action"/>
    <button type="submit" value="another non-default action"/>
    <button type="submit" value="yet another non-default action"/>
    <button type="submit" value="still another non-default action"/>

    <button type="submit" value="default action"/>
</form>

Since the W3C spec indicates multiple submit buttons are valid, but omits guidance as to how the user-agent should handle them, the browser manufacturers are left to implement as they see fit. I've found they'll either submit the first submit button in the form, or submit the next submit button after the form field that currently has focus.

由于W3C规范指出多个提交按钮是有效的,但是省略了用户代理应该如何处理它们的指导,浏览器制造商可以根据自己的需要来实现它们。我发现他们要么在表单中提交第一个提交按钮,要么在当前有焦点的表单字段之后提交下一个提交按钮。

Unfortunately, simply adding a style of display: none; won't work because the W3C spec indicates any hidden element should be excluded from user interactions. So hide it in plain sight instead!

不幸的是,只需添加一种显示样式:none;无法工作,因为W3C规范指出任何隐藏的元素都应该被排除在用户交互之外。所以,把它藏在显眼的地方吧!

Above is an example of the solution I ended up putting into production. Hitting the enter key triggers the default form submission is behavior as expected, even when other non-default values are present and precede the default submit button in the DOM. Bonus for mouse/keyboard interaction with explicit user inputs while avoiding javascript handlers.

上面是我最终投入生产的解决方案的一个例子。按下enter键会触发默认表单提交,这是预期的行为,即使在DOM中出现其他非默认值并先于默认提交按钮时也是如此。使用显式用户输入进行鼠标/键盘交互,同时避免使用javascript处理程序。

Note: tabbing through the form will not display focus for any visual element yet will still cause the invisible button to be selected. To avoid this issue, simply set tabindex attributes accordingly and omit a tabindex attribute on the invisible submit button. While it may seem out of place to promote these styles to !important, they should prevent any framework or existing button styles from interfering with this fix. Also, those inline styles are definitely poor form, but we're proving concepts here... not writing production code.

注意:通过表单制表将不会显示任何可视元素的焦点,但仍然会导致选择不可见按钮。为了避免这个问题,只需相应地设置tabindex属性,并在不可见的submit按钮上省略一个tabindex属性。虽然它看起来不适合推广这些样式,但是它们应该阻止任何框架或现有的按钮样式来干扰这个修复。而且,这些内联样式确实很糟糕,但是我们在这里证明了一些概念……不写产品代码。

#3


50  

HTML 4 does not make it explicit. The current HTML5 working draft specifies that the first submit button must be the default:

HTML 4并没有明确说明它。当前的HTML5工作草案规定,第一个提交按钮必须是默认的:

A form element's default button is the first submit button in tree order whose form owner is that form element.

表单元素的默认按钮是树中的第一个提交按钮,其表单所有者是该表单元素。

If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.

如果用户代理支持让用户隐式提交表单(例如,在一些平台上按下“输入”键集中隐式提交表单文本框时),那么这样做的一种默认按钮定义了激活行为必须导致用户代理运行合成默认按钮的点击激活步骤。

#4


16  

I think this post would help if someone wants to do it with jQuery:

如果有人想用jQuery,我觉得这篇文章会有所帮助:

http://greatwebguy.com/programming/dom/default-html-button-submit-on-enter-with-jquery/

http://greatwebguy.com/programming/dom/default-html-button-submit-on-enter-with-jquery/

The basic solution is:

基本的解决方案是:

$(function() {
    $("form input").keypress(function (e) {
    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
        $('input[type=submit].default').click();
        return false;
    } else {
        return true;
    }
    });
});

and another I liked was:

另一个我喜欢的是:

jQuery(document).ready(function() {
$("form input, form select").live('keypress', function (e) {
if ($(this).parents('form').find('button[type=submit].default, input[type=submit].default').length <= 0)
return true;

if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$(this).parents('form').find('button[type=submit].default, input[type=submit].default').click();
return false;
} else {
return true;
}
});
}); 

#5


6  

I had a form with 11 submit buttons on it, and it would always use the first submit button when the user pressed enter. I read elsewhere that it is not a good idea (bad practice) to have more than one submit button on a form, and the best way to do this is have the button you want as default, as the only submit button on the form. The other buttons should be made into "TYPE=BUTTON" and an onClick event added that calls your own submit routine in Javascript. Something like this :-

我有一个包含11个提交按钮的表单,当用户按下enter时,它总是使用第一个提交按钮。我在别处读到过,在表单上有多个提交按钮不是一个好主意(不好的实践),最好的方法是将您想要的按钮作为默认设置,作为表单上惟一的提交按钮。其他按钮应该被设置为“TYPE=BUTTON”,并添加一个onClick事件,该事件在Javascript中调用您自己的提交例程。这样的:-

<SCRIPT Language="JavaScript">
function validform()
{
  // do whatever you need to validate the form, and return true or false accordingly
}

function mjsubmit()
{
  if (validform()) { document.form1.submit(); return true;}
  return false;
}
</SCRIPT>
<INPUT TYPE=BUTTON NAME="button1" VALUE="button1" onClick="document.form1.submitvalue='button1'; return mjsubmit();">
<INPUT TYPE=BUTTON NAME="button2" VALUE="button2" onClick="document.form1.submitvalue='button2'; return mjsubmit();">
<INPUT TYPE=SUBMIT NAME="button3" VALUE="button3" onClick="document.form1.submitvalue='button3'; return validform();">
<INPUT TYPE=BUTTON NAME="button4" VALUE="button4" onClick="document.form1.submitvalue='button4'; return mjsubmit();">

Here, button3 is the default, and although you are programmatically submitting the form with the other buttons, the mjsubmit routine validates them. HTH.

在这里,button3是默认值,尽管您正在用其他按钮以编程方式提交表单,但是mjsubmit例程会验证它们。HTH。

#6


4  

This can now be solved using flexbox:

现在可以用flexbox解决这个问题:

HTML

HTML

<form>
    <h1>My Form</h1>
    <label for="text">Input:</label>
    <input type="text" name="text" id="text"/>

    <!-- Put the elements in reverse order -->
    <div class="form-actions">
        <button>Ok</button> <!-- our default action is first -->
        <button>Cancel</button>
    </div>
</form>

CSS

CSS

.form-actions {
    display: flex;
    flex-direction: row-reverse; /* reverse the elements inside */
}

Explaination
Using flex box, we can reverse the order of the elements in a container that uses display: flex by also using the CSS rule: flex-direction: row-reverse. This requires no CSS or hidden elements. For older browsers that do not support flexbox, they still get a workable solution but the elements will not be reversed.

通过使用flex box进行解释,我们可以通过使用CSS规则:flex-direction: row-reverse来逆转使用display: flex的容器中的元素的顺序。这不需要CSS或隐藏元素。对于不支持flexbox的旧浏览器,他们仍然可以得到一个可行的解决方案,但是元素不会被逆转。

Demo
http://codepen.io/Godwin/pen/rLVKjm

演示http://codepen.io/Godwin/pen/rLVKjm

#7


2  

I struggled with the same question since i had submit button in the middle of the from which redirected submit to another page, like so:

由于我在重定向提交到另一个页面的中间有一个submit按钮,所以我一直在思考同样的问题,如下所示:

<button type="submit" onclick="this.form.action = '#another_page'">More</button>

When user pressed enter key, this button was clicked instead of another submit button.

当用户按下enter键时,这个按钮被点击而不是另一个提交按钮。

So i did some primitive tests by creating a from with multiple submit buttons and different visibility options and onclick event alerting which button was clicked: https://jsfiddle.net/aqfy51om/1/

所以我做了一些原始的测试,通过创建一个包含多个提交按钮和不同可见性选项的from,以及onclick事件提醒按钮被单击:https://jsfiddle.net/aqfy51om/1/

Browsers and OS'es i used for testing:

我用于测试的浏览器和操作系统:

WINDOWS

窗户

  • Google Chrome 43 (c'mon google :D)
  • 谷歌Chrome 43(来吧谷歌:D)
  • Mozilla Firefox 38
  • Mozilla Firefox 38
  • Internet Explorer 11
  • Internet Explorer 11
  • Opera 30.0
  • Opera 30.0

OSX

OSX

  • Google Chrome 43
  • Google Chrome 43
  • Safari 7.1.6
  • Safari 7.1.6

Most of these browsers clicked very first button despite the visibility options applied exept IE and Safari which clicked the third button, which is "visible" inside "hidden" container:

大多数浏览器都点击了第一个按钮,尽管应用了exept IE和Safari,点击了第三个按钮,在“隐藏”容器中是“可见的”:

<div style="width: 0; height: 0; overflow: hidden;">
    <button type="submit" class="btn btn-default" onclick="alert('Hidden submit button #3 was clicked');">Hidden submit button #3</button>
</div>

So my suggestion, which i'm going to use myself, is:

所以我的建议,我将会用到我自己,是:

If you form has multiple submit buttons with different meaning, then include submit button with default action at the beginning of the form which is either:

如果您的表单有多个不同含义的提交按钮,则在表单的开头包含带有默认动作的提交按钮,即:

  1. Fully visible
  2. 完全可见
  3. Wrapped in a container with style="width: 0; height: 0; overflow: hidden;"
  4. 用样式="宽度:0 "的容器包装;高度:0;溢出:隐藏。”

EDIT Another option might be to offset the button(still at the beginning of the from) style="position: absolute; left: -9999px; top: -9999px;", just tried it in IE - worked , but i have no idea what else it can screw up, for example printing..

编辑另一个选项可能是偏移按钮(仍然在from开头)style="position: absolute;左:-9999 px;前:-9999像素;",刚在IE下试过,但我不知道它还能搞砸什么,比如打印……

#8


1  

From your comments:

从你的评论:

A consequence is that, if you have multiple forms submitting to the same script, you can't rely on submit buttons to distinguish them.

结果是,如果有多个表单提交给同一个脚本,就不能依靠提交按钮来区分它们。

I drop an <input type="hidden" value="form_name" /> into each form.

我将放入每个表单。

If submitting with javascript: add submit events to forms, not click events to their buttons. Saavy users don't touch their mouse very often.

如果使用javascript提交:将提交事件添加到表单,而不是单击事件到它们的按钮。Saavy用户不经常触摸他们的鼠标。

#9


1  

When you have multiple submit buttons in a single form and a user presses the ENTER key to submit the form from a text field, this code overrides default functionality, by calling the submit event on the form from the key press event. Here is that code:

当您在一个表单中有多个提交按钮,并且用户按ENTER键从文本字段提交表单时,此代码通过从键按事件调用表单上的submit事件来覆盖默认功能。是代码:

$('form input').keypress(function(e){

    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)){ $(e.target).closest('form').submit(); return false; }
    else return true;

});

#10


1  

Strange that the first button Enter goes always to the first button regardless is visible or not, e.g. using jquery show/hide(). Adding attribute .attr('disabled', 'disabled') prevent receiving Enter submit button completely. It's problem for example when adjusting Insert/Edit+Delete button visibility in record dialogs. I found less hackish and simple placing Edit in front of Insert

奇怪的是,第一个按钮输入总是指向第一个按钮,不管它是否可见,例如使用jquery show/hide()。添加属性.attr('disabled', 'disabled')可完全阻止接收Enter submit按钮。例如,在记录对话框中调整插入/编辑+删除按钮的可见性是一个问题。我发现在插入前放置编辑器不那么容易

<button type="submit" name="action" value="update">Update</button>
<button type="submit" name="action" value="insert">Insert</button>
<button type="submit" name="action" value="delete">Delete</button>

and use javascript code:

并使用javascript代码:

$("#formId button[type='submit'][name='action'][value!='insert']").hide().attr('disabled', 'disabled');
$("#formId button[type='submit'][name='action'][value='insert']").show().removeAttr('disabled');

#11


0  

my recipe:

我的食谱:

<form>
<input type=hidden name=action value=login><!-- the magic! -->

<input type=text name=email>
<input type=text name=password>

<input type=submit name=action value=login>
<input type=submit name=action value="forgot password">
</form>

It will send the default hidden field if none of the buttons are 'clicked'.

如果没有一个按钮是“单击”的,它将发送默认的隐藏字段。

if they are clicked, they have preference and it's value is passed.

如果它们被单击,它们有首选项,并传递它的值。

#12


0  

Another solution I've used is to just have one button in the form, and fake the other buttons.

我使用的另一种解决方案是在表单中只有一个按钮,然后伪造其他按钮。

Here's an example:

这里有一个例子:

<form>
  <label for="amount">Amount of items</label>
  <input id="amount" type="text" name="amount" />
  <span id="checkStock" class="buttonish">Check stock</span>
  <button type="submit" name="action" value="order">Place order</button>
</form>

I then style the span elements to look like a button. A JS listener observes the span and performs the desired operation once clicked.

然后将span元素样式化为一个按钮。JS侦听器会观察跨度,并在单击后执行所需的操作。

Not necessarily right for all situations, but at least it's pretty easy to do.

不一定适用于所有情况,但至少很容易做到。

#13


0  

From the HTML 4 spec:

来自HTML 4规范:

If a form contains more than one submit button, only the activated submit button is successful.

如果表单包含多个submit按钮,则只有激活的submit按钮是成功的。

This means that given more than 1 submit button and none activated (clicked), none should be successful.

这意味着,如果提交按钮超过1个,且没有激活(单击),则不应该成功。

And I'd argue this makes sense: Imagine a huge form with multiple submit-buttons. At the top, there is a "delete this record"-button, then lots of inputs follow and at the bottom there is an "update this record"-button. A user hitting enter while in a field at the bottom of the form would never suspect that he implicitly hits the "delete this record" from the top.

我认为这是有道理的:想象一个有多个提交按钮的巨大表单。在顶部,有一个“删除这个记录”按钮,然后大量的输入跟随,在底部有一个“更新这个记录”按钮。当用户在表单底部的字段中点击进入时,绝不会怀疑他从顶部隐去了“删除这条记录”。

Therefore I think it is not a good idea to use the first or any other button it the user does not define (click) one. Nevertheless, browsers are doing it of course.

因此,我认为使用用户没有定义(单击)的第一个或其他按钮不是一个好主意。不过,浏览器当然会这么做。

#14


-2  

EDIT: Sorry, when writing this answer I was thinking about submit buttons in the general sense. The answer below is not about multiple type="submit" buttons, as it leaves only one type="submit" and change the other to type="button". I leave the answer here as reference in case helps someone that can change the type in their form:

编辑:对不起,当我写这个答案的时候,我在考虑一般意义上的提交按钮。下面的答案不是关于多个type="submit"按钮,因为它只留下一个type="submit",而将另一个改为type="button"。我把答案留在这里作为参考,以防有人可以改变他们的形式:

To determine what button is pressed when hitting enter, you can mark it up with type="submit", and the other buttons mark them with type="button". For example:

要确定按enter时按了哪个按钮,可以用type="submit"标记它,其他按钮用type="button"标记它们。例如:

<input type="button" value="Cancel" />
<input type="submit" value="Submit" />