Stop form Submission (Posting) on Enter Key Press

This is a quick hit post. If you are developing a form in ASP.NET you may be noticed that when we press enter key even without writing any information in textboxes, form gets post (submitted). So, how do you stop it?
You can achieve this by simple JavaScript code, here it is:

    <script type="text/javascript">
        //Stop Form Submission of Enter Key Press
        function stopRKey(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")) { return false; }
        }
        document.onkeypress = stopRKey;
    </script>

You need to place above code in <head> section of the web page.

Comments

  1. It's very useful in few scenarios.

    ReplyDelete
  2. AMAZING...

    thank you very much..... it works perfectly...
    being looking for a solution for over a week now...

    ReplyDelete
  3. hello sir!
    how to reset all field values in an asp page without making use of the input rest control already given.?

    ReplyDelete
  4. Also make sure you do not set defaultbutton property of Page.Form

    ReplyDelete
  5. There is no need to put script in head tag. You can just register using registerClientScriptBlock method. Also make sure not to set defaultbutton property of Page.Form

    ReplyDelete

Post a Comment

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System