我在一个网站上有一个调查,用户按下回车键(我不知道为什么),不小心没有点击提交按钮就提交了调查(表单),这似乎有些问题。有办法防止这种情况吗?

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


当前回答

一个漂亮的简单的jQuery解决方案:

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

其他回答

我想添加一些CoffeeScript代码(没有经过现场测试):

$ ->
    $(window).bind 'keypress', (event) ->
        if event.keyCode == 13
            unless {'TEXTAREA', 'SELECT'}[event.originalEvent.srcElement.tagName]
                event.preventDefault()

(我希望你喜欢这个“除非”从句中的妙招。)

Use:

// Validate your form using the jQuery onsubmit function... It'll really work...

$(document).ready(function(){
   $(#form).submit(e){
       e.preventDefault();
       if(validation())
          document.form1.submit();
   });
});

function validation()
{
   // Your form checking goes here.
}

<form id='form1' method='POST' action=''>
    // Your form data
</form>

我需要防止只提交特定的输入,所以我使用了一个类选择器,让它成为我需要的“全局”特性。

<input id="txtEmail" name="txtEmail" class="idNoEnter" .... />

jQuery代码:

$('.idNoEnter').keydown(function (e) {
  if (e.keyCode == 13) {
    e.preventDefault();
  }
});

或者,如果keydown不够用:

$('.idNoEnter').on('keypress keydown keyup', function (e) {
   if (e.keyCode == 13) {
     e.preventDefault();
   }
});

一些注意事项:

在这里修改各种不错的答案,Enter键似乎适用于所有浏览器的keydown。对于替代方法,我将bind()更新为on()方法。

我是类选择器的忠实粉丝,权衡所有的利弊和性能讨论。我的命名约定是'idSomething',表示jQuery将其用作id,以将其与CSS样式分开。

在我的特定情况下,我必须停止ENTER提交表单,并模拟单击提交按钮。这是因为提交按钮上有一个点击处理程序,因为我们在一个模态窗口中(继承了旧代码)。在任何情况下,这是我的组合解。

    $('input,select').keypress(function(event) {
        // detect ENTER key
        if (event.keyCode == 13) {
            // simulate submit button click
            $("#btn-submit").click();
            // stop form from submitting via ENTER key press
            event.preventDefault ? event.preventDefault() : event.returnValue = false;
        }
    });

这个用例对于使用IE8的人特别有用。

第4.10.22.2节隐式提交的W3C 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. Note: Consequently, if the default button is disabled, the form is not submitted when such an implicit submission mechanism is used. (A button has no activation behavior when disabled.)

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

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

这种方法的一个很好的特性是它不需要JavaScript;无论是否启用JavaScript,都需要一个符合标准的web浏览器来防止隐式表单提交。