如何防止在基于web的应用程序中按ENTER键提交表单?


当前回答

[2012修订版,没有内联处理程序,保留textarea进入处理]

function checkEnter(e){
 e = e || event;
 var txtArea = /textarea/i.test((e.target || e.srcElement).tagName);
 return txtArea || (e.keyCode || e.which || e.charCode || 0) !== 13;
}

现在你可以在表单上定义一个按键处理程序: <形式[…onkeypress="return checkEnter(event)">

document.querySelector('form').onkeypress = checkEnter;

其他回答

我花了一些时间制作这款跨浏览器,适用于IE8、9、10、Opera 9+、Firefox 23、Safari(PC)和Safari(MAC)

示例:http://jsfiddle.net/greatbigmassive/ZyeHe/

基本代码-通过“onkeypress”附加到您的窗体和传递窗口调用此函数。事件”。

function stopEnterSubmitting(e) {
    if (e.keyCode == 13) {
        var src = e.srcElement || e.target;
        if (src.tagName.toLowerCase() != "textarea") {
            if (e.preventDefault) {
                e.preventDefault();
            } else {
                e.returnValue = false;
            }
        }
    }
}

I Have come across this myself because I have multiple submit buttons with different 'name' values, so that when submitted they do different things on the same php file. The enter / return button breaks this as those values aren't submitted. So I was thinking, does the enter / return button activate the first submit button in the form? That way you could have a 'vanilla' submit button that is either hidden or has a 'name' value that returns the executing php file back to the page with the form in it. Or else a default (hidden) 'name' value that the keypress activates, and the submit buttons overwrite with their own 'name' values. Just a thought.

防止“ENTER”提交表单可能会给一些用户带来不便。所以你最好按照下面的步骤来做:

在你的表单标签中写入'onSubmit'事件:

<form name="formname" id="formId" onSubmit="return testSubmit()" ...>
 ....
 ....
 ....
</form>

编写Javascript函数如下:

function testSubmit(){
  if(jQuery("#formId").valid())
      {
        return true;
      }
       return false;

     } 

     (OR)

不管是什么原因,如果你想阻止按Enter键提交表单,你可以用javascript写下面的函数:

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

谢谢。

ENTER键仅仅激活表单的默认提交按钮,这将是第一个

<input type="submit" />

浏览器在表单中查找。

所以不要有提交按钮,而是类似的东西

<input type="button" value="Submit" onclick="submitform()" /> 

编辑:回应评论中的讨论:

如果只有一个文本字段,这就行不通了——但在这种情况下,这可能是理想的行为。

另一个问题是,这依赖于Javascript来提交表单。从可访问性的角度来看,这可能是一个问题。这可以通过用javascript编写<input type='button'/>来解决,然后在<noscript>标签中放入<input type='submit' />。这种方法的缺点是,对于禁用javascript的浏览器,您将在ENTER时提交表单。在这种情况下,由OP决定期望的行为是什么。

我知道没有办法做到这一点而不调用javascript。

只需从onsubmit处理程序返回false

<form onsubmit="return false;">

或者如果你想要一个中间的处理程序

<script>
var submitHandler = function() {
  // do stuff
  return false;
}
</script>
<form onsubmit="return submitHandler()">