jQuery 通过按 Enter 防止用户提交表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/895171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:04:03  来源:igfitidea点击:

Prevent users from submitting a form by hitting Enter

jqueryhtmlformsform-submit

提问by DForck42

I have a survey on a website, and there seems to be some issues with the users hitting enter (I don't know why) and accidentally submitting the survey (form) without clicking the submit button. Is there a way to prevent this?

我在网站上进行了一项调查,用户按 Enter(我不知道为什么)并在没有单击提交按钮的情况下意外提交了调查(表单),这似乎存在一些问题。有没有办法防止这种情况?

I'm using HTML, PHP 5.2.9, and jQuery on the survey.

我在调查中使用 HTML、PHP 5.2.9 和 jQuery。

回答by

You can use a method such as

您可以使用一种方法,例如

$(document).ready(function() {
  $(window).keydown(function(event){
    if(event.keyCode == 13) {
      event.preventDefault();
      return false;
    }
  });
});

In reading the comments on the original post, to make it more usable and allow people to press Enterif they have completed all the fields:

在阅读原始帖子的评论时,为了使其更有用,并允许人们在Enter完成所有字段后按下:

function validationFunction() {
  $('input').each(function() {
    ...

  }
  if(good) {
    return true;
  }
  return false;
}

$(document).ready(function() {
  $(window).keydown(function(event){
    if( (event.keyCode == 13) && (validationFunction() == false) ) {
      event.preventDefault();
      return false;
    }
  });
});

回答by BalusC

Disallow enter key anywhere

禁止在任何地方输入密钥

If you don't have a <textarea>in your form, then just add the following to your <form>:

如果您<textarea>的表单中没有 a ,则只需将以下内容添加到您的<form>:

<form ... onkeydown="return event.key != 'Enter';">

Or with jQuery:

或者使用 jQuery:

$(document).on("keydown", "form", function(event) { 
    return event.key != "Enter";
});

This will cause that every key press inside the form will be checked on the key. If it is not Enter, then it will return trueand anything continue as usual. If it is Enter, then it will return falseand anything will stop immediately, so the form won't be submitted.

这将导致表单内的每一次按键都将在key. 如果不是Enter,那么它将返回true并且一切照常继续。如果是Enter,那么它将返回false并且任何事情都会立即停止,因此不会提交表单。

The keydownevent is preferred over keyupas the keyupis too late to block form submit. Historically there was also the keypress, but this is deprecated, as is the KeyboardEvent.keyCode. You should use KeyboardEvent.keyinstead which returns the name of the key being pressed. When Enteris checked, then this would check 13 (normal enter) as well as 108 (numpad enter).

keydown事件优于keyup作为keyup是来不及块的形式提交。从历史上看,也有keypress,但已弃用,KeyboardEvent.keyCode. 您应该使用它KeyboardEvent.key来代替它返回被按下的键的名称。当Enter被选中时,则这将检查13(正常输入),以及108(数字键盘输入)。

Note that $(window)as suggested in some other answers instead of $(document)doesn't work for keydown/keyupin IE<=8, so that's not a good choice if you're like to cover those poor users as well.

请注意,$(window)正如其他一些答案中所建议的那样,而不是在 IE<=8 中$(document)keydown/不起作用keyup,因此如果您也想覆盖那些可怜的用户,这不是一个好的选择。

Allow enter key on textareas only

仅允许在 textarea 上输入键

If you have a <textarea>in your form (which of course shouldaccept the Enter key), then add the keydown handler to every individual input element which isn't a <textarea>.

如果您<textarea>的表单中有 a (当然应该接受 Enter 键),那么将 keydown 处理程序添加到每个不是<textarea>.

<input ... onkeydown="return event.key != 'Enter';">
<select ... onkeydown="return event.key != 'Enter';">
...

To reduce boilerplate, this is better to be done with jQuery:

为了减少样板文件,最好使用 jQuery 来完成:

$(document).on("keydown", ":input:not(textarea)", function(event) {
    return event.key != "Enter";
});

If you have other event handler functions attached on those input elements, which you'd also like to invoke on enter key for some reason, then only prevent event's default behavior instead of returning false, so it can properly propagate to other handlers.

如果您在这些输入元素上附加了其他事件处理程序函数,并且出于某种原因您还想在 enter 键上调用这些函数,那么只阻止事件的默认行为而不是返回 false,这样它就可以正确地传播到其他处理程序。

$(document).on("keydown", ":input:not(textarea)", function(event) {
    if (event.key == "Enter") {
        event.preventDefault();
    }
});

Allow enter key on textareas and submit buttons only

仅允许在 textarea 上输入键并提交按钮

If you'd like to allow enter key on submit buttons <input|button type="submit">too, then you can always refine the selector as below.

如果您也希望在提交按钮上允许输入键<input|button type="submit">,那么您可以随时优化选择器,如下所示。

$(document).on("keydown", ":input:not(textarea):not(:submit)", function(event) {
    // ...
});

Note that input[type=text]as suggested in some other answers doesn't cover those HTML5 non-text inputs, so that's not a good selector.

请注意,input[type=text]正如其他一些答案中所建议的那样,没有涵盖那些 HTML5 非文本输入,因此这不是一个好的选择器。

回答by Daniel Trebbien

Section 4.10.22.2 Implicit submissionof the W3C HTML5 spec says:

第 4.10.22.2 节隐式提交W3C HTML5 规范说:

A formelement's default buttonis the first submit buttonin tree orderwhose form owneris that formelement.

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 buttonhas a defined activation behaviormust cause the user agent to run synthetic click activation stepson that default button.

Note:Consequently, if the default buttonis disabled, the form is not submitted when such an implicit submission mechanism is used. (A button has no activation behaviorwhen disabled.)

一个form元素的默认按钮是第一个提交按钮树形结构顺序,其所属表单form元素。

如果用户代理支持让用户隐式提交表单(例如,在某些平台上,在文本字段聚焦时点击“输入”键隐式提交表单),则为默认按钮具有定义激活的表单执行此操作行为必须导致用户代理在该默认按钮运行合成点击激活步骤

注意:因此,如果禁用默认按钮,则在使用这种隐式提交机制时不会提交表单。(按钮在禁用时没有激活行为。)

Therefore, a standards-compliant way to disable any implicit submission of the form is to place a disabled submit button as the first submit button in the form:

因此,禁用表单任何隐式提交的符合标准的方法是将禁用的提交按钮作为表单中的第一个提交按钮:

<form action="...">
  <!-- Prevent implicit submission of the form -->
  <button type="submit" disabled style="display: none" aria-hidden="true"></button>

  <!-- ... -->

  <button type="submit">Submit</button>
</form>

One nice feature of this approach is that it works without JavaScript; whether or not JavaScript is enabled, a standards-conforming web browser is required to prevent implicit form submission.

这种方法的一个很好的特点是它可以在没有 JavaScript 的情况下工作;无论是否启用 JavaScript,都需要符合标准的 Web 浏览器来防止隐式表单提交。

回答by Upgradingdave

I had to catch all three events related to pressing keys in order to prevent the form from being submitted:

为了防止提交表单,我必须捕获与按键相关的所有三个事件:

    var preventSubmit = function(event) {
        if(event.keyCode == 13) {
            console.log("caught ya!");
            event.preventDefault();
            //event.stopPropagation();
            return false;
        }
    }
    $("#search").keypress(preventSubmit);
    $("#search").keydown(preventSubmit);
    $("#search").keyup(preventSubmit);

You can combine all the above into a nice compact version:

您可以将以上所有内容组合成一个不错的紧凑版本:

    $('#search').bind('keypress keydown keyup', function(e){
       if(e.keyCode == 13) { e.preventDefault(); }
    });

回答by Tom Hubbard

If you use a script to do the actual submit, then you can add "return false" line to the onsubmit handler like this:

如果您使用脚本进行实际提交,那么您可以像这样向 onsubmit 处理程序添加“return false”行:

<form onsubmit="return false;">

Calling submit() on the form from JavaScript will not trigger the event.

从 JavaScript 调用表单上的 submit() 不会触发该事件。

回答by Buzogany Laszlo

Use:

用:

$(document).on('keyup keypress', 'form input[type="text"]', function(e) {
  if(e.keyCode == 13) {
    e.preventDefault();
    return false;
  }
});

This solution works on all forms on a website (also on forms inserted with Ajax), preventing only Enters in input texts. Place it in a document ready function, and forget this problem for a life.

此解决方案适用于网站上的所有表单(也适用于使用 Ajax 插入的表单),仅防止Enter输入文本中出现 s。把它放在一个文档就绪函数中,一辈子忘掉这个问题。

回答by bbmud

Instead of preventing users from pressing Enter, which may seem unnatural, you can leave the form as is and add some extra client-side validation: When the survey is not finished the result is not sent to the server and the user gets a nice message telling what needs to be finished to complete the form. If you are using jQuery, try the Validation plugin:

Enter您可以保持表单不变并添加一些额外的客户端验证,而不是阻止用户按下,这可能看起来不自然,而是添加一些额外的客户端验证:当调查未完成时,结果不会发送到服务器,用户会收到一条很好的消息告诉需要完成什么才能完成表格。如果您使用 jQuery,请尝试验证插件:

http://docs.jquery.com/Plugins/Validation

http://docs.jquery.com/Plugins/Validation

This will require more work than catching the Enterbutton, but surely it will provide a richer user experience.

这将需要比捕捉Enter按钮更多的工作,但肯定会提供更丰富的用户体验。

回答by sparklos

I can't comment yet, so I'll post a new answer

我还不能发表评论,所以我会发布一个新的答案

Accepted answer is ok-ish, but it wasn't stopping submit on numpad enter. At least in current version of Chrome. I had to alter the keycode condition to this, then it works.

接受的答案是好的,但它并没有停止在数字键盘输入上提交。至少在当前版本的 Chrome 中。我不得不将键码条件更改为此,然后它就可以工作了。

if(event.keyCode == 13 || event.keyCode == 169) {...}

回答by Eonasdan

A nice simple little jQuery solution:

一个不错的简单小jQuery解决方案:

$("form").bind("keypress", function (e) {
    if (e.keyCode == 13) {
        return false;
    }
});

回答by Developer

It is my solution to reach the goal, it is clean and effective.

这是我达到目标的解决方案,它干净而有效。

$('form').submit(function () {
  if ($(document.activeElement).attr('type') == 'submit')
     return true;
  else return false;
});