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


当前回答

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.

其他回答

如果这些答案都不适合你,试试这个。在实际提交表单的按钮之前添加一个提交按钮,对事件什么都不做。

HTML

<!-- The following button is meant to do nothing. This button will catch the "enter" key press and stop it's propagation. -->
<button type="submit" id="EnterKeyIntercepter" style="cursor: auto; outline: transparent;"></button>

JavaScript

$('#EnterKeyIntercepter').click((event) => {
    event.preventDefault(); //The buck stops here.
    /*If you don't know what this if statement does, just delete it.*/
    if (process.env.NODE_ENV !== 'production') {
        console.log("The enter key was pressed and captured by the mighty Enter Key Inceptor (⌐■_■)");
    }
});

在我的案例中,这个jQuery JavaScript解决了这个问题

jQuery(function() {
            jQuery("form.myform").submit(function(event) {
               event.preventDefault();
               return false;
            });
}

你将不得不调用这个函数,它将取消表单的默认提交行为。您可以将它附加到任何输入字段或事件。

function doNothing() {  
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if( keyCode == 13 ) {


    if(!e) var e = window.event;

    e.cancelBubble = true;
    e.returnValue = false;

    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
}

防止“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;
              }
           });
         });

谢谢。

我也遇到了同样的问题(表单包含大量的文本字段和不熟练的用户)。

我是这样解决的:

function chkSubmit() {
    if (window.confirm('Do you want to store the data?')) {
        return true;
    } else {
        // some code to focus on a specific field
        return false;
    }
}

在HTML代码中使用这个:

<form
    action="go.php" 
    method="post"
    accept-charset="utf-8"  
    enctype="multipart/form-data"
    onsubmit="return chkSubmit()"
>

通过这种方式,ENTER键按计划工作,但需要确认(通常是第二次按ENTER键)。

我留给读者的任务是,如果用户决定继续使用表单,那么脚本会将用户发送到按ENTER的字段中。