/ html

Browsers automatically submit single input field forms on enter (and how to fix that)

Normally browsers will not submit forms when the enter key is pressed. You have to implement this kind of feature via JavaScript (and you probably did already at some point). However if your form only has ONE single input field most browsers will submit the form when the enter key is pressed. You don't even need a submit button for this to happen. This is deeply rooted in the HTML 2.0 specification (you can read about this here). I guess it is supposed to be some kind of feature. I found it very frustrating because I didn't want my form to be submitted when the enter key is press and I tried everything to prevent this from happening, from unbinding the key events to blocking the event from bubbling up. Nothing helped. It took me quiet a while until I figured out that this is because my form only has one input field. Apparently, there is only one way to solve this problem. Right, you guessed it, add another input field and hide it via CSS:

<form action="/search.php" method="get">
	<input type="text" name="keyword" />
	<input type="text" name="formsubmitfix" style="display: none;" />
</form>

This will make it work. But you end up with a messy url when submitting the form: /search.php?keyword=test&formsubmitfix;=. This is not a very satisfying solution. Making the input a hidden field will not work either:

<form action="/search.php" method="get">
	<input type="text" name="keyword" />
	<input type="hidden" name="formsubmitfix" />
</form>

Despite the fact that the resulting URL is still messy, it also doesnt prevent the form from being submitted when the enter key is pressed. What does help is the following:

<form action="/search.php" method="get">
	<input type="text" name="keyword" />
	<input type="text" style="display: none;" />
</form>

Hide the input field via CSS and don't give it a name. This way the browser recognizes multiple input fields but the resulting URL does not contain the input field we added to fix the problem, voilá: /search.php?keyword=test
Exactly what we wanted :-)

comments powered by Disqus