Why is it that a <form>
with a single <input>
field will reload the form when the user enters a value and presses the Enter, and it does not if there are 2 or more fields in the <form>
?.
I wrote a simple page to test this oddity.
If you enter a value in the second form and press Enter, you'll see it reloads the page passing the entered value as if you called GET
. why? and how do I avoid it?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>testFormEnter</title>
</head>
<body>
<form>
<input type="text" name="partid2" id="partid2" />
<input type="text" name="partdesc" id="partdesc" />
</form>
<p>2 field form works fine</p>
<form>
<input type="text" name="partid" id="partid" />
</form>
<p>One field form reloads page when you press the Enter key why</p>
</body>
</html>
as vineet already said, this is rooted in the html 2.0 specification:
here is how to prevent this from happening without screwing up your urls:
The solution I found for all of the browsers that I tested (IE, FF, Chrome, Safari, Opera) is that the first input
type=submit
element on the form has to be visible and has to be the first element in the form. I was able to use CSS placement to move the submit button to the bottom of the page and it did not affect the results!This is a known bug in IE6/7/8. It doesn't appear that you will get a fix for it.
The best workaround you can do for this, is to add another hidden field (if your engineering conscience permits). IE will no longer auto-submit a form when it finds that there are two input-type fields in the form.
Update
In case you were wondering why this is the case, this gem comes straight out of the HTML 2.0 specification (Section 8.2):
It's not reloading the page as such, it's submitting the form.
However, in this example because you have no action attribute on the form it submits to itself which gives the impression of reloading the page.
Also, I can't repro the behaviour you describe. If I am in any text input in a form and I press Enter it submits the form, no matter where in the form the input is located or how many inputs there are.
You might want to try this out some more in different browsers.
I handled this by the following code but I am not sure if this a good approach. By looking for input fields in a given form and if its 1 prevent the default action.
Yes, form with a single inputText field working as different in HTML 4.
onSubmit return false not working for me but the below fix bug is working fine