开发者

How to disable auto submit behavior when hitting enter key?

I want to hit enter key to go to p2.htm or p3.htm according to the input text that I was typing in. And I also want to hit submit1 button to alert('no1') manually.

It works in FireFox, but in IE6, when I hit enter key it will submit the submit button.

How can I make the thing right in IE 6 as it is in FireFox?

I use javascript and 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>


If using MVC3, you can disable submitting via Enter by editing the BeginForm call as follows:

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


<form onsubmit="return false"></form>

This will stop the form proceeding to the next page after either by clicking a submit button or pressing enter.


The problem with the accepted solution is that normal submit buttons no longer work. You must script all the buttons.

<form onsubmit="return false"></form>

Here's a better solution that doesn't break non javascript submit buttons. This solution simply tells the browser to not do default behavior when a user hits the enter key on form inputs.

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


This function should do the trick:

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;
}

You should call it like this:

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


Change the input type from "submit" to "button"


<%@taglib uri="/struts-tags"  prefix="s" %>
<html>
<head>
    <script type="text/javascript">
        function stopsubmit()
        {
            document.ourform.onsubmit="return true";
        }
        function pup()
        {
            return true;
        }
    </script>
</head>
<body>
    <form action="sa.jsp" name="ourform" onsubmit="return false">
        <s:submit action="" onclick="stopsubmit()" theme="simple"></s:submit>
    </form>
</body>


You can do by using :

<script type="text/javascript">
    $(document).ready(function() {
       $(".div/formClass").bind("keypress", function(e) {
          if (e.keyCode == 13) {
             return false;
          }
       });
    });
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜