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


当前回答

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

我是这样解决的:

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

其他回答

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.

我在这里或其他帖子中找到的所有关于这个主题的答案都有一个缺点,那就是它阻止了表单元素上的实际更改触发器。所以如果你运行这些解决方案,onchange事件也不会被触发。为了克服这个问题,我修改了这些代码,并为自己开发了以下代码。我希望这对其他人有用。 我给了一个类我的表单“prevent_auto_submit”,并添加以下JavaScript:

$(document).ready(function() 
{
    $('form.prevent_auto_submit input,form.prevent_auto_submit select').keypress(function(event) 
    { 
        if (event.keyCode == 13)
        {
            event.preventDefault();
            $(this).trigger("change");
        }
    });
});

放入javascript外部文件

   (function ($) {
 $(window).keydown(function (event) {  

    if (event.keyCode == 13) {

        return false;
    }
});

 })(jQuery);

或者在body tag里面

<script>


$(document).ready(function() {
    $(window).keydown(function(event) {
        alert(1);

        if(event.keyCode == 13) {

            return false;
        }
    });
});

</script>

只需从onsubmit处理程序返回false

<form onsubmit="return false;">

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

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

我花了一些时间制作这款跨浏览器,适用于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;
            }
        }
    }
}