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!!


advertise here


JavaScript 4185637510312489733

Post a Comment


Currency Converter

Built using AngularJS and ASP.NET Web API