Originally posted by glenngv
A: When there is only one text field and it has focus when you press Enter, the form is automatically submitted. That is even if there is no submit buttons, even with normal button, it will cause the form to be submitted. The solution is to have a dummy field. But of course, the dummy field must not be visible to the user. If you make it as hidden field (<input type="hidden" />), the form will still be submitted. But if you make a normal text field and set its CSS
display to
none, the form will not be submitted. Try running the demo below:
Code:
<html>
<head>
<title>How do I prevent the page from submitting a form when the user presses Enter key in a field?</title>
</head>
<body>
<form name="test">
<h3>How do I prevent the page from submitting a form when the user presses Enter key in a field?</h3>
<input name="txt1" />
<input type="button" value="Submit" />
<input type="text" name="dummy" style="display:none" />
</form>
</body>
</html>
Of course, you can use also id or class selectors to define the CSS display for that field.
CSS:
Code:
#dummy {display:none;}
HTML:
Code:
<input type="text" name="dummy" id="dummy" />
or
CSS:
Code:
.hide {display:none;}
HTML:
Code:
<input type="text" name="dummy" class="hide" />