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


当前回答

简单地添加这个属性到你的FORM标签:

onsubmit="return gbCanSubmit;"

然后,在你的SCRIPT标签中,添加这个:

var gbCanSubmit = false;

然后,当你创建一个按钮或出于任何其他原因(比如在函数中)你最终允许提交时,只需翻转全局布尔值并执行.submit()调用,类似于下面的示例:

function submitClick(){

  // error handler code goes here and return false if bad data

  // okay, proceed...
  gbCanSubmit = true;
  $('#myform').submit(); // jQuery example

}

其他回答

只需从onsubmit处理程序返回false

<form onsubmit="return false;">

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

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

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

我是这样解决的:

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的字段中。

这个链接提供了一个在Chrome、FF和IE9以及IE7和ie8的模拟器(IE9的开发者工具(F12)中为我工作过的解决方案。

http://webcheatsheet.com/javascript/disable_enter_key.php

//Turn off submit on "Enter" key

$("form").bind("keypress", function (e) {
    if (e.keyCode == 13) {
        $("#btnSearch").attr('value');
        //add more buttons here
        return 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.