views:

834

answers:

3

Hello, I am trying to use onkeypress on an input type="text" control to fire off some javascript if the enter button is pressed. It works on most pages, but I also have some pages with custom .NET controls.

The problem is that the .NET submit fires before the onkeypress. Does anybody have an insight on how to make onkeypress fire first?

If it helps, here is my javascript:

 function SearchSiteSubmit(myfield, e)
{
 var keycode;
 if (window.event)
  keycode = window.event.keyCode;
 else if (e)
  keycode = e.which;
 else 
  return true;
 if (keycode == 13)
 {
  SearchSite();
  return false;
 }
 else 
  return true;
}
A: 

Javascript OnKeyPress will always fire first, it's more a case of wether or not it has completed its operation before the page is posted back..

I would say rethink what is going on and where.. What is taking place at the server side?

Rob Cooper
Thanks, the onkeypress fires the function above which then fires searchsite which is an adaptation of Google's CSE code. So i suppose the roundtrip to Google to perform the search might be taking longer than .NET just doing whatever.
Jim
Actually, I had only onkeypress="SearchSiteSubmit()" adding return (onkeypress="return SearchSiteSubmit()" made it work.
Jim
A: 

This isn't a very clear question so I'll give it a shot --

It looks like you're looking for a keypress of "enter" here. The problem seems to be that the "enter" key is usually bound to the submit button on a form automatically by the browser, which means that when the user presses enter, you submit the form, rather than running the javascript you have here. What you should do is make a global event handler that checks to see if "MyField" has the focus when the enter button is pressed, and if so, then fire the javascript, rather than submitting the form. I Hope I understood your question!

Plan B
A: 

How are you assigning the javascript?

It should look like:

<input id="TextID" type="text" onkeypress="return SearchSiteSubmit('TextID', event)" />
Interesting.. So what difference does adding the "return" make? Is it because the function has a return value?
Rob Cooper