View Single Post
Old 01-10-2005, 10:50 AM   PM User | #14
liorean
The thread killer


 
Join Date: Feb 2003
Location: Umeå, Sweden
Posts: 5,575
Thanks: 0
Thanked 84 Times in 75 Posts
liorean will become famous soon enoughliorean will become famous soon enough
Q: How to prevent form from submitting when the user press enter?

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" />

Last edited by liorean; 01-10-2005 at 10:54 AM..
liorean is offline