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


当前回答

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

其他回答

将这个标签添加到你的表单- onsubmit="return false;" 然后只能使用JavaScript函数提交表单。

stopSubmitOnEnter (e) {
  var eve = e || window.event;
  var keycode = eve.keyCode || eve.which || eve.charCode;

  if (keycode == 13) {
    eve.cancelBubble = true;
    eve.returnValue = false;

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

    return false;
  }
}

然后在表格上:

<form id="foo" onkeypress="stopSubmitOnEnter(e);">

不过,如果不使用突兀的JavaScript会更好。

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.

你会发现这更简单和有用:D

$(document).on('submit', 'form', function(e){
    /* on form submit find the trigger */
    if( $(e.delegateTarget.activeElement).not('input, textarea').length == 0 ){
        /* if the trigger is not between selectors list, return super false */
        e.preventDefault();
        return false;
    } 
});

我认为,你可以在javascript的表单中捕获键下,防止冒泡。网页上的ENTER基本上只是提交当前所选控件所在的表单。