Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does forms with single input field submit upon pressing enter key in input

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>
like image 339
sdfor Avatar asked Sep 02 '09 20:09

sdfor


People also ask

How do I stop form submission on Enter key?

Disallow enter key anywhereon("keydown", "form", function(event) { return event. key != "Enter"; }); This will cause that every key press inside the form will be checked on the key .

How do I make a form so it can be submitted by hitting Enter in HTML?

HTML form submit on Enter Key | Example code You don't need to use JavaScript to do submit button or input on entering key pressed. Just need to mark it up with type="submit" , and the other buttons mark them with type="button" .


2 Answers

This is a little known "Quirk" that has been out for a while. I know some people have resolved it in various ways.

The easiest bypass in my opinion is to simply have a second input that isn't displayed to the user. Granted not all that user friendly on the backend, it does work to resolve the issue.

I should note that the most common place that I hear of this issue is with IE specifically and not with FireFox or others. Although it does seem to affect them as well.

like image 142
Mitchel Sellers Avatar answered Oct 23 '22 08:10

Mitchel Sellers


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):

When there is only one single-line text input field in a form, the user agent should accept Enter in that field as a request to submit the form.

like image 50
Vineet Reynolds Avatar answered Oct 23 '22 08:10

Vineet Reynolds