Disable Form Submit/PostBack on Enter Key Press

Sometimes, when there are multiple text input fields in the form it is undesirable that the  form gets submitted when the user hits "ENTER" key in a field. You may want to disable this behavior and have enter key enabled on a particular text field alone or you may want to completely disable form submission on enter key press event. You can achieve this by handling the enter key press event in javascript. 

To do this, write the below javascript code in your web page. This piece of code will block the enter key in all browsers 4.0 above, except when enter key is pressed in a Textarea or on the Submit button itself.

<script language="JavaScript">
   var nav = window.Event ? true : false;
   if (nav) {
        window.onkeydown = NetscapeEventHandler_KeyDown;
   } else {
        document.onkeydown = MicrosoftEventHandler_KeyDown;

   function NetscapeEventHandler_KeyDown(e) {
       if (e.which == 13 && e.target.type != 'textarea' && e.target.type != 'submit') { 
           return false; 
           return true;

   function MicrosoftEventHandler_KeyDown() {
       if (event.keyCode == 13 && event.srcElement.type != 'textarea' && 
            event.srcElement.type!= 'submit')
             return false;
       return true;

We can also do this by setting default button in ASP.NET and by setting 'UseSubmitBehaviour='false' property for every other button except the default one. But the above code is more generalized and can be used in any language. 

 Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. Thanks for reading this!!



JavaScript 4185637510312489733

Post a Comment

  1. Can you help me with the solution to preventing a form submiting when pressing "enter" inside a textfield/area.

    The form do not submit when pressing enter, when the mouse curser is outside a textfield/area which is fine.

    But i need help with adding a function to a textfield/area that prevents the form for submiting, so it only uses the submit button.

  2. http://javascript.happycodings.com/ has too many js codes

  3. how to disable postback on hitting enter key on all textbox of a page pls answer me