Microsoft KB Archive/298498

= How To Prevent Form Submission When User Presses the ENTER Key on a Form =

Article ID: 298498

Article Last Modified on 5/17/2007

-

APPLIES TO


 * Microsoft Internet Explorer 4.0 128-Bit Edition
 * Microsoft Internet Explorer 4.01 Service Pack 2
 * Microsoft Internet Explorer 4.01 Service Pack 1
 * Microsoft Internet Explorer 4.01 Service Pack 2
 * Microsoft Internet Explorer 5.0
 * Microsoft Internet Explorer 5.01
 * Microsoft Internet Explorer (Programming) 5.01 SP1
 * Microsoft Internet Explorer 5.5

-



This article was previously published under Q298498



SUMMARY
When the focus is on an HTML form, and the user presses the ENTER key, by default, Internet Explorer treats this action as if the user clicks Submit. However, not all browsers behave the same way, and you may want to disable this behavior. This article demonstrates how to use script to prevent this behavior.



MORE INFORMATION
The following steps demonstrate how to handle the onkeydown event for the INPUT element and cancel the event altogether to prevent Internet Explorer from submitting the form submission when a user presses the ENTER key.   In your favorite HTML editor, create a new HTML file named Test.htm, and paste the following code:    function testForEnter {       if (event.keyCode == 13) {               event.cancelBubble = true; event.returnValue = false; } }  



 Form1: Does not stop form submission when user presses ENTER key.   </FORM>

<FORM id=&quot;FORM2&quot; name=&quot;FORM2&quot; method=&quot;GET&quot; action=&quot;testSubmit.htm&quot; style=&quot;background-color:lightblue&quot;> Form2: Stops form submission when user presses ENTER key.</H3> <INPUT id=&quot;text2&quot; name=&quot;text2&quot; onkeydown=&quot;testForEnter;&quot;> <INPUT type=&quot;submit&quot; value=&quot;Submit&quot;> </FORM>

</BODY>

</HTML> </li> <li> Create another HTML file named testSubmit.htm, and paste the following code: <HTML>  <SCRIPT LANGUAGE=&quot;javascript&quot;> window.onload = window_onload; function window_onload {   alert (&quot;The form has submitted.&quot;); } </SCRIPT> </HEAD>

<BODY> <DIV align=&quot;center&quot;>This is testSubmit.htm.</DIV> </BODY> </HTML> </li> <li>In Internet Explorer, browse to Test.htm.</li> <li>Set focus to the text box inside &quot;Form1,&quot; and then press the ENTER key. Notice that the form is submitted because this is the default behavior.</li> <li>In Internet Explorer, browse back to Test.htm.</li> <li>Set focus to the text box inside &quot;Form2,&quot; and then press the ENTER key. Notice that the form is not submitted. When you look at the code behind the onclick event, notice that you cancel the navigation by canceling the event.</li></ol>

<div class="references_section">