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

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


当前回答

Use:

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

这个解决方案适用于网站上的所有表单(也适用于使用Ajax插入的表单),只防止输入文本中的enter。把它放在文档就绪函数中,然后永远忘记这个问题。

其他回答

一种完全不同的方法:

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>

没有提交按钮也行。只需在输入(type=button)中放入一个脚本,如果希望它提交表单中的数据,则添加eventListener。

而是使用这个

<input type="button" onclick="event.preventDefault();this.closest('form').submit();">

而不是用这个

<input type="submit">

注意:这里需要onclick在点击时实际提交表单。默认情况下,type="button"不足以提交。

您可以创建一个JavaScript方法来检查是否按下了Enter键,如果按下了,就停止提交。

<script type="text/javascript">
  function noenter() {
  return !(window.event && window.event.keyCode == 13); }
</script>

只需在submit方法上调用它。

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

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

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

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

你可以把上面所有的组合成一个漂亮的紧凑版本:

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