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:
<HTML>
<HEAD>
<SCRIPT LANGUAGE="javascript">
function testForEnter()
{
if (event.keyCode == 13)
{
event.cancelBubble = true;
event.returnValue = false;
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM id="FORM1" name="FORM1" method="GET" action="testSubmit.htm"
style="background-color:yellow">
<H3>Form1: Does not stop form submission when user presses ENTER key.</H3>
<INPUT id="text1" name="text1">
<INPUT type="submit" value="Submit">
</FORM>
<FORM id="FORM2" name="FORM2" method="GET" action="testSubmit.htm"
style="background-color:lightblue">
<H3>Form2: Stops form submission when user presses ENTER key.</H3>
<INPUT id="text2" name="text2" onkeydown="testForEnter();">
<INPUT type="submit" value="Submit">
</FORM>
</BODY>
</HTML>
- Create another HTML file named testSubmit.htm, and paste the following code:
<HTML>
<HEAD>
<SCRIPT LANGUAGE="javascript">
window.onload = window_onload;
function window_onload()
{
alert ("The form has submitted.");
}
</SCRIPT>
</HEAD>
<BODY>
<DIV align="center">This is testSubmit.htm.</DIV>
</BODY>
</HTML>
- In Internet Explorer, browse to Test.htm.
- Set focus to the text box inside "Form1," and then press the ENTER key. Notice that the form is submitted because this is the default behavior.
- In Internet Explorer, browse back to Test.htm.
- Set focus to the text box inside "Form2," 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.