As an ASP.NET developer, you might find it pretty common to have more than one form on a web page, sometimes you decide so, sometimes you just inherit a design and have to make it work. Let's just put the case where we have a form on the master page area, like a “search” or a “subscribe” button, and our inner page is a simple form with some fields to collect user information and submit it back to our site, like the image below.
Both forms will cause well-formed postbacks to the server if you click on the Search or the Submit button; however, if you are typing on a textbox and you hit Enter, anything could happen. You might have inadvertently submitted form 1 instead of form 2, or vice versa.
Changing the default button of the page is simple and will help you if you know which button will be the one to respond to the Enter key all the time. If you are using ASP.NET, just one line of code and you are done.
this.form1.DefaultButton = searchButton.UniqueID;
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && ((node.type == "text") ||
(node.type == "password")))
document.onkeypress = forgetEnterKey;
And this should be enough. Well, users will have to click on buttons, but at least they won’t submit the wrong data by mistake.