Javascript:在Enter Key按下提交阻止表单
问题描述:
我有一个网页,当我点击回车键时,我有两个表格,我正在调用一个javascript函数来强制页面加载另一个页面。我的代码是
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;
}
和
$(document).ready(function()
{
$("#frmUserListSearch").keyup(function(event)
{
if(event.keyCode == 13)
{
SearchUser();
}
});
});
但页面正在填写表格在调用SearchUSer函数时提交。我在alert中获取了正确的url。但是页面没有加载到浏览器中
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
任何想法???
提前致谢
答
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:
您只需要:
$(document).ready(function()
{
$("#frmUserListSearch").keyup(function(event)
{
if(event.keyCode == 13)
{
SearchUser();
if (e.preventDefault)
e.preventDefault();
else e.returnValue = false;
}
});
});
编辑以反映评论