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


当前回答

这对我很管用。 onkeydown = "返回! (event.keyCode = = 13)”

    <form id="form1" runat="server" onkeydown="return !(event.keyCode==13)">

   </form>

其他回答

[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;
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会更好。

简单地添加这个属性到你的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

}

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键提交web表单?

$(“.pc_prevent_submit”)时函数(){ 美元(窗口).keydown(函数(事件){ 如果事件。keyCode == 13) { event.preventDefault (); 返回错误; } }); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> <form class= " pc_prevent_submit " action= " " method= " post " > <input type= " text " name= " username " > <input type= " password " name= " userpassword " > <input type= " submit " value= " submit " > > < /形式