Click here to Skip to main content
Click here to Skip to main content

Disable Enter key on web pages with multiple forms

, 24 Aug 2011
Rate this:
Please Sign up or sign in to vote.
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.

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;

However, this might not work smoothly across different browsers and in some cases, it turns out you might decide to completely disable the Enter key on the page, how do you do that? Well, you can use JavaScript and add it to your regular page or master page. See the fragment below:

function forgetEnterKey(evt)
{
    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")))
    {
        return false;
    }
} 
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Leonardo Paneque
Team Leader
United States United States
Leonardo loves to code with C# and thinks .NET platforms rocks.
He has a Master degree in Computer Sciences and likes to share code and ideas.
Follow on   Twitter

Comments and Discussions

 
QuestionSpecial thanks PinprofessionalAKS 00711-Jun-14 23:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140709.1 | Last Updated 24 Aug 2011
Article Copyright 2011 by Leonardo Paneque
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid