Take the 2-minute tour ×

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;
		return true;
	if (keycode == 13)
		return false;
		return true;
share|improve this question

3 Answers 3

up vote 0 down vote accepted

How are you assigning the javascript?

It should look like:

<input id="TextID" type="text" onkeypress="return SearchSiteSubmit('TextID', event)" />
share|improve this answer
Interesting.. So what difference does adding the "return" make? Is it because the function has a return value? –  Rob Cooper Dec 10 '08 at 8:05

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?

share|improve this answer
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 Dec 9 '08 at 16:50
Actually, I had only onkeypress="SearchSiteSubmit()" adding return (onkeypress="return SearchSiteSubmit()" made it work. –  Jim Dec 9 '08 at 17:07

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!

share|improve this answer

Your Answer


