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

发布于 2024-07-22 15:05:15 字数 1831 浏览 4 评论 0原文

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

  • 通过
  • 在 JS 中使用 HTMLFormElement.submit()

Enter ,浏览器应该如何确定多个提交中的哪一个按钮(如果有)用作按下的按钮?

这在两个层面上很重要:

  • 调用附加到提交按钮的 onclick 事件处理程序
  • 将数据发送回 Web 服务器

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

  • 当按 Enter 时,Firefox、Opera 和 Safari 在按 Enter 时使用表单中的第一个提交按钮
  • ,IE 使用第一个提交按钮或根本不使用第一个提交按钮,具体取决于我无法弄清楚
  • 所有这些的 情况浏览器根本不使用任何 JS 提交

标准是怎么说的?

如果有帮助,这是我的测试代码(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>

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

  • by pressing Enter
  • using HTMLFormElement.submit() in JS

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
  • the data sent back to the web server

My experiments so far have shown that:

  • when pressing Enter, Firefox, Opera and Safari use the first submit button in the form
  • 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
  • all these browsers use none at all for a JS submit

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)

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

丑疤怪 2024-07-29 15:05:15

我认为如果有人想用 jQuery 来做这件事,这篇文章会有所帮助:

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

基本的解决方案是:

$(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;
    }
    });
});

另一个我喜欢的是:

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

I think this post would help if someone wants to do it 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;
        }
    });
});
等数载,海棠开 2024-07-29 15:05:15

如果您通过 JavaScript 提交表单(即 formElement.submit() 或任何等效内容),则所有提交按钮都不会被视为成功,并且不会包含任何值在提交的数据中。 (请注意,如果您使用 submitElement.click() 提交表单,那么您引用的提交将被视为活动的;这实际上并不属于您的问题的范围,因为这里提交按钮是明确的,但我想我应该为那些阅读第一部分并想知道如何通过 JavaScript 表单提交成功提交按钮的人添加它。当然,表单的 onsubmit 处理程序仍然会以这种方式触发,但它们不会。通过 form.submit() 所以这又是一锅鱼...)

如果在非文本区域字段中通过按 Enter 键提交表单,那么实际上由用户代理来决定什么它想要这里。 规范没有提及任何有关提交表单的信息在文本输入字段中使用 Enter 键(如果您按 Tab 切换到按钮并使用空格或其他方式激活它,那么就没有问题,因为明确使用了特定的提交按钮)。 它只是说,当激活提交按钮时必须提交表单。 甚至不需要在文本输入中按 Enter 即可提交表单。

我相信 Internet Explorer 选择源代码中首先出现的提交按钮; 我有一种感觉,Firefox 和 Opera 选择具有最低 tabindex 的按钮,如果没有定义其他内容,则回退到第一个定义的按钮。 关于提交是否具有非默认值属性 IIRC 也存在一些复杂性。

需要注意的是,这里发生的情况没有明确的标准,并且完全取决于浏览器的突发奇想 - 因此无论您在做什么,都应尽可能避免依赖任何特定行为。 如果您确实必须知道,您可能可以找出各种浏览器版本的行为,但是当我不久前对此进行调查时,发现了一些相当复杂的条件(当然,这些条件可能会随着新的浏览器版本而变化),我会建议您尽可能避免!

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 JavaScript 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...)

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

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.

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!

等往事风中吹 2024-07-29 15:05:15

HTML 4 并没有使其明确。 HTML 5 指定第一个提交按钮必须是默认按钮< /a>:

4.10.21.2 隐式提交

form 元素的默认按钮是第一个提交按钮,采用树形顺序< /a> 的 表单所有者 是 <代码>表单元素。

如果用户代理支持让用户隐式提交表单
(例如,在某些平台上,在输入文本时按“Enter”键
控件聚焦隐式提交表单),然后这样做
表单,其默认按钮具有激活行为并且不是
禁用,必须导致用户代理触发 click 事件< /a> 那时
默认按钮

如果您想在保持视觉顺序的同时影响哪个是“第一”,那么您可以采取几种方法。

屏幕外、不可聚焦的按钮。

.hidden-default {
    position: absolute;
    left: -9999px;
}
<form>
  <input name="text">
  <button name="submit" value="wanted" class="hidden-default" tabindex="-1"></button>
  <button name="submit" value="not wanted">Not the default</button>
  <button name="submit" value="wanted">Looks like the default</button>
</form>

弹性盒订单:

.ordering {
    display: inline-flex;
}

.ordering button {
    order: 2;
}

.ordering button + button {
    order: 1;
}
<form>
  <input name="text">
  <div class="ordering">
    <button name="submit" value="wanted">First in document order</button>
    <button name="submit" value="not wanted">Second in document order</button>
  </div>
</form>

HTML 4 does not make it explicit. HTML 5 specifies that the first submit button must be the default:

4.10.21.2 Implicit submission

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
control is focused implicitly submits the form), then doing so for a
form, whose default button has activation behavior and is not
disabled, must cause the user agent to fire a click event at that
default button.

If you want to influence which one is "first" while maintaining the visual order then there are a couple of approaches you could take.

An off-screen, unfocusable button.

.hidden-default {
    position: absolute;
    left: -9999px;
}
<form>
  <input name="text">
  <button name="submit" value="wanted" class="hidden-default" tabindex="-1"></button>
  <button name="submit" value="not wanted">Not the default</button>
  <button name="submit" value="wanted">Looks like the default</button>
</form>

Flexbox order:

.ordering {
    display: inline-flex;
}

.ordering button {
    order: 2;
}

.ordering button + button {
    order: 1;
}
<form>
  <input name="text">
  <div class="ordering">
    <button name="submit" value="wanted">First in document order</button>
    <button name="submit" value="not wanted">Second in document order</button>
  </div>
</form>

遗忘曾经 2024-07-29 15:05:15

Andrezj 的回答几乎已经解决了......但这里有一个简单的跨浏览器解决方案。

采用如下形式:

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

并重构为:

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

由于 W3C 规范指示多个提交按钮有效,但忽略了有关用户代理应如何处理它们的指导,浏览器制造商只能按照他们认为合适的方式实施。 我发现他们要么提交表单中的第一个提交按钮,要么在当前具有焦点的表单字段之后提交下一个提交按钮。

不幸的是,简单地添加 display: none; 样式是行不通的,因为 W3C 规范指示任何隐藏元素都应从用户交互中排除。 因此,请将其隐藏在众目睽睽之下!

上面是我最终投入生产的解决方案的示例。 按 Enter 键会触发默认表单提交,即使存在其他非默认值并且位于 DOM 中的默认提交按钮之前也是如此。 与显式用户输入的鼠标/键盘交互的好处,同时避免 JavaScript 处理程序。

注意:按 Tab 键浏览表单不会显示任何视觉元素的焦点,但仍会导致选择不可见的按钮。 为了避免这个问题,只需相应地设置 tabindex 属性,并在不可见的提交按钮上省略 tabindex 属性。 虽然将这些样式提升为 !important 似乎不太合适,但它们应该防止任何框架或现有按钮样式干扰此修复。 另外,这些内联样式绝对是糟糕的形式,但我们在这里证明概念......而不是编写生产代码。

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

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

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!

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.

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.

囍孤女 2024-07-29 15:05:15

现在可以使用 Flexbox 来解决这个问题:

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

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

解释

使用 Flexbox,我们可以反转元素的顺序在使用 display: flex 的容器中,同时使用 CSS 规则:flex-direction: row-reverse。 这不需要 CSS 或隐藏元素。 对于不支持 Flexbox 的旧浏览器,他们仍然可以获得可行的解决方案,但元素不会颠倒。

演示

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

This can now be solved using Flexbox:

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

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

Explanation

Using Flexbox, 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.

Demo

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

夏末的微笑 2024-07-29 15:05:15

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

这是一个示例:

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

然后我将 span 元素设置为看起来像按钮。 JavaScript 侦听器观察范围并在单击后执行所需的操作。

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

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 JavaScript listener observes the span and performs the desired operation once clicked.

It’s not necessarily right for all situations, but at least it’s pretty easy to do.

野稚 2024-07-29 15:05:15

我有一个带有 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();">

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

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:

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

谈情不如逗狗 2024-07-29 15:05:15
<form onsubmit="alert('submit');return false;">
    <input name="username">
    <input name="password" type="password">
    <button onclick="if(document.activeElement === this){alert('button 1');}else{default_submit.click();}return false;">button 1</button>
    <button onclick="if(document.activeElement === this){alert('button 2');}else{default_submit.click();}return false;">button 2</button>
    <input id="default_submit" type="submit">
</form>

如果您在文本输入中按 Enter,则该按钮将不会获得焦点。 然后我们忽略这个点击,而是点击默认的提交,但是如果你用鼠标点击按钮,它会获得焦点,然后我们应用这个点击。

演示:https://codepen.io/remon-reffat/pen/mdRaXbp

<form onsubmit="alert('submit');return false;">
    <input name="username">
    <input name="password" type="password">
    <button onclick="if(document.activeElement === this){alert('button 1');}else{default_submit.click();}return false;">button 1</button>
    <button onclick="if(document.activeElement === this){alert('button 2');}else{default_submit.click();}return false;">button 2</button>
    <input id="default_submit" type="submit">
</form>

If you press Enter from text input, then the button will not become focused. Then we ignore this click and click the default submit instead, but if you click the button by mouse, it will be focused, then we apply this click.

Demo: https://codepen.io/remon-reffat/pen/mdRaXbp

自在安然 2024-07-29 15:05:15

我遇到了同样的问题,因为我在表单中间有一个提交按钮,它将提交重定向到另一个页面,如下所示:

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

当用户按下 Enter 键时,会单击此按钮而不是另一个按钮提交按钮。

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

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

Windows

OS X

尽管应用了可见性选项,大多数浏览器还是单击了第一个按钮除了 Internet Explorer 和 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>

所以我自己要使用的建议是:

如果您的表单有多个具有不同含义的提交按钮,则在表单开头包含一个具有默认操作的提交按钮,该按钮是:

  1. 完全可见
  2. 包裹在一个带有 style="width: 0; 的容器 高度:0; 溢出:隐藏;”

另一种选择可能是偏移按钮(仍在 from 的开头)style="position:absolute; 左:-9999px; top: -9999px;",刚刚在 Internet Explorer 中尝试过 - 有效,但我不知道它还会搞砸什么,例如打印。

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

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

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

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

Browsers and OSes I used for testing:

Windows

OS X

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

<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 your form has multiple submit buttons with different meanings, then include a submit button with the default action at the beginning of the form which is either:

  1. Fully visible
  2. Wrapped in a container with style="width: 0; height: 0; overflow: hidden;"

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 Internet Explorer - worked , but I have no idea what else it can screw up, for example printing..

静待花开 2024-07-29 15:05:15

根据您的评论:

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

我将 放入每个表单中。

如果使用 JavaScript 提交:将提交事件添加到表单,而不是添加到按钮的单击事件。 精明的用户不会经常触摸鼠标。

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. Savvy users don't touch their mouse very often.

酒几许 2024-07-29 15:05:15

当单个表单中有多个提交按钮并且用户按 Enter 键从文本字段提交表单时,此代码将通过从按键调用表单上的提交事件来覆盖默认功能新闻发布会。 这是该代码:

$('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;
});

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:

$('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;
});
舞袖。长 2024-07-29 15:05:15

奇怪的是,第一个按钮 Enter 总是转到第一个按钮,无论是否可见,例如使用 jQuery show/hide()。 添加属性 .attr('disabled', 'disabled') 完全阻止接收 Enter 提交按钮。 例如,在调整记录对话框中的“插入/编辑+删除”按钮可见性时,就会出现问题。 我发现将 Edit 放在 Insert 前面比较简单,

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

并且使用 JavaScript 代码:

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

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 the Enter submit button completely. It's a problem for example when adjusting the Insert/Edit+Delete button visibility in record dialogs. I found it less hackish and simple placing Edit in front of Insert:

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

$("#formId button[type='submit'][name='action'][value!='insert']").hide().attr('disabled', 'disabled');
$("#formId button[type='submit'][name='action'][value='insert']").show().removeAttr('disabled');
初懵 2024-07-29 15:05:15

我的秘诀:

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

如果没有任何按钮被“单击”,它将发送默认的隐藏字段。

如果单击其中一个,则它具有优先权并且其值被传递。

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 one is clicked, it has preference and its value is passed.

梦开始←不甜 2024-07-29 15:05:15

来自 HTML 4 规范

如果表单包含多个提交按钮,则仅激活已激活的提交按钮
提交按钮成功。

这意味着如果有多个提交按钮并且没有激活(单击)按钮,则任何提交按钮都不会成功。

我认为这是有道理的:

想象一个带有多个提交按钮的巨大表单。 在顶部,有一个“删除此记录”按钮,然后是许多输入,在底部有一个“更新此记录”按钮。 用户在表单底部的字段中按 Enter 时,永远不会怀疑他/她隐式地从顶部点击了“删除此记录”。

因此,我认为使用第一个按钮或用户未定义(单击)的任何其他按钮不是一个好主意。 尽管如此,浏览器当然正在这样做。

From the HTML 4 specification:

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

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

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/she 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.

半步萧音过轻尘 2024-07-29 15:05:15

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

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

抱歉,在写这个答案时,我正在考虑一般意义上的提交按钮。 下面的答案不是关于多个 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:

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文