如何在按Enter键时禁用自动提交行为?

Mik*_*108 12 javascript button

我想根据我输入的输入文本按Enter键转到p2.htm或p3.htm.我还想手动点击submit1按钮提醒('no1').

它适用于FireFox,但在IE6中,当我按下回车键时,它将提交提交按钮.

我怎样才能在IE 6中使用FireFox中的东西?

我使用javascript和jQuery.

<input id="Text2"  type="text"  onkeyup="if(event.keyCode==13){go2();}" /> 
<input id="Text3"  type="text"  onkeyup="if(event.keyCode==13){go3();}" /> 

<input id="submit1"  type="submit" value="submit" onclick="alert('no1')" />

<script type="text/javascript">
    function go2()
    {
        window.location = "p2.htm";
    }
    function go3()
    {
        window.location = "p3.htm";
    }
</script>
Run Code Online (Sandbox Code Playgroud)

WEF*_*EFX 33

如果使用MVC3,您可以通过编辑BeginForm调用来禁用通过Enter提交,如下所示:

@using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Post, new { onkeydown = "return event.keyCode!=13" }))
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 这里最简单的方法就像魅力一样! (3认同)
  • 这将禁用表单内textarea上的回车键。 (2认同)

Jak*_*xon 26

<form onsubmit="return false"></form>
Run Code Online (Sandbox Code Playgroud)

这将通过单击提交按钮或按Enter键停止表单进入下一页.

  • 如果我只想在输入密钥上禁用提交,但我想保持点击提交怎么办? (4认同)

Joj*_*ojo 8

这个功能应该可以解决问题:

function submitOnEnter(e, page) {
    var key;

    if (window.event)
        key = window.event.keyCode; //IE
    else
        key = e.which; //Firefox & others

    if(key == 13)
        window.location = page;
}
Run Code Online (Sandbox Code Playgroud)

你应该这样称呼它:

<input id="Text2"  type="text"  onkeyup="submitOnEnter(event, 'p2.html')" /> 
Run Code Online (Sandbox Code Playgroud)


小智 6

接受的解决方案的问题是正常的提交按钮不再起作用.您必须编写所有按钮的脚本.

<form onsubmit="return false"></form>
Run Code Online (Sandbox Code Playgroud)

这是一个更好的解决方案,不会破坏非JavaScript提交按钮.当用户点击表单输入上的回车键时,此解决方案只是告诉浏览器不执行默认行为.

// prevent forms from auto submitting on all inputs
$(document).on("keydown", "input", function(e) {
  if (e.which==13) e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)


Kon*_*Kon 5

将输入类型从"提交"更改为"按钮"