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

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


当前回答

这对我很有用

jQuery.each($("#your_form_id").find('input'), function(){
    $(this).bind('keypress keydown keyup', function(e){
       if(e.keyCode == 13) { e.preventDefault(); }
    });
});

其他回答

一种完全不同的方法:

The first <button type="submit"> in the form will be activated on pressing Enter. This is true even if the button is hidden with style="display:none; The script for that button can return false, which aborts the submission process. You can still have another <button type=submit> to submit the form. Just return true to cascade the submission. Pressing Enter while the real submit button is focussed will activate the real submit button. Pressing Enter inside <textarea> or other form controls will behave as normal. Pressing Enter inside <input> form controls will trigger the first <button type=submit>, which returns false, and thus nothing happens.

因此:

<form action="...">
  <!-- insert this next line immediately after the <form> opening tag -->
  <button type=submit onclick="return false;" style="display:none;"></button>

  <!-- everything else follows as normal -->
  <!-- ... -->
  <button type=submit>Submit</button>
</form>

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

接受的答案是ok-ish,但它不是停止提交在numpad进入。至少在当前版本的Chrome中是这样。我不得不改变这个键码条件,然后它工作。

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

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>

这是完美的方式,你不会从你的页面重定向

$('form input').keydown(function (e) {
if (e.keyCode == 13) {
    e.preventDefault();
    return false;
}
});

使用Javascript(不检查任何输入字段):

<script>
window.addEventListener('keydown', function(e) {
    if (e.keyIdentifier == 'U+000A' || e.keyIdentifier == 'Enter' || e.keyCode == 13) {
        e.preventDefault();
        return false;
    }
}, true);
</script>

如果有人想将此应用于特定的字段,例如输入类型text:

<script>
window.addEventListener('keydown', function(e) {
    if (e.keyIdentifier == 'U+000A' || e.keyIdentifier == 'Enter' || e.keyCode == 13) {
        if (e.target.nodeName == 'INPUT' && e.target.type == 'text') {
            e.preventDefault();
            return false;
        }
    }
}, true);
</script>

这对我来说很有效。