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


当前回答

请查看这篇文章如何防止按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 " > > < /形式

其他回答

请查看这篇文章如何防止按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 " > > < /形式

以下是我的做法:

window.addEventListener('keydown', function(event)
{
    if (event.key === "Enter" && event.target.tagName !== 'TEXTAREA')
    {
        if(event.target.type !== 'submit')
        {
            event.preventDefault();
            return false;
        }
    }
});

如何:

<script>
function isok(e) {
  var name = e.explicitOriginalTarget.name;
  if (name == "button") {
    return true
  }
  return false;
}
</script>
<form onsubmit="return isok(event);">
<input type="text" name="serial"/>
<input type="submit" name="button" value="Create Thing"/>
</form>

只要给你的按钮命名,它仍然会提交,但文本字段,即显式originaltarget,当你在其中点击返回时,将没有正确的名称。

只需从onsubmit处理程序返回false

<form onsubmit="return false;">

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

<script>
var submitHandler = function() {
  // do stuff
  return false;
}
</script>
<form onsubmit="return submitHandler()">
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会更好。