[removed]Block form submit on Enter Key press

2019-06-08 02:58发布

问题:

I have a web page where i have 2 forms when i click the enter key, I am calling a javascript function to force the page to load another page.My code is

function SearchUser()
{
var text = document.getElementById("searchItem").value;
text = text == "" ? -1 : text;
var by = document.getElementById("listBy").value;   
var on="";
if(by==1)
{
    on="USERNAME";
}
else if(by==2)
{
    on="FIRSTNAME";
}
else if(by==3)
{
    on="EMAIL_ID";
}

gotoUrl="userlist.php?searchItem="+text+"&onSearch="+on; 
    alert(gotoUrl); 
window.navigate=gotoUrl;

}

and

$(document).ready(function()
{
 $("#frmUserListSearch").keyup(function(event)
 {
  if(event.keyCode == 13)
  { 
    SearchUser();
  }
 });

});

But the page is doing a form submit when the SearchUSer function being called.I am getting the correct url in the alert.But The page is not loading in the brower

Any Ideas ???

Thanks in advance

回答1:

if (document.addEventListener) {
    document.getElementById('strip').addEventListener('keypress',HandleKeyPress,false);
} else {
    document.getElementById('strip').onkeypress = HandleKeyPress;
}

function HandleKeyPress(e) {
    switch (e.keyCode) {
        case e.DOM_VK_ENTER:
        if (e.preventDefault)
            e.preventDefault();
    else e.returnValue = false;
    }
}

EDIT due to original Question edit:

all you need is:

$(document).ready(function()
{
    $("#frmUserListSearch").keyup(function(event)
        {
            if(event.keyCode == 13)
            {     
                SearchUser();
                if (e.preventDefault)
                    e.preventDefault();
                else e.returnValue = false;
            }
        });
});

edited to reflect comment



回答2:

Returning false often does the trick.

http://javascript.about.com/library/bldisdef.htm



回答3:

I have two recommendations. First, use the keydown event instead of keyup (it catches "enter" before submit better). Second, in your SearchUser() function, use window.location instead of window.navigate to go to the other page.

$(document).ready(function() {
  $("#frmUserListSearch").keydown(function(event) {
     if(event.keyCode == 13){    
       SearchUser();
       return false;
     }
  });
});

NOTE: Don't forget to remove the "alert()" inside the SearchUser() function as it causes the form to submit before navigating away from the page.



回答4:

You can do this by using the action attribute of the form, without having to deal with key events, granted that you will later need javascript to take action on the control that submits the form.

  <html>
     <head>
        <script type="text/javascript">
           function donothing() {}
        </script>
     <body>
        <form action='javascript:donothing()'>
           ...
        </form>
     </body>
  </html>