views:

3216

answers:

3

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  A: 

Returning false often does the trick.

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

Matthew Vines
return false after window.navigate, i tried.Didnt work
Shyju
The event has to return false. So I would put it after SearchUser();
Matthew Vines
+2  A: 
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

Jonathan Fingland
Do i need to pout the code in the page load ?
Shyju
+1  A: 

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.

Jose Basilio
@Shyju - did you try this?
Jose Basilio