Things I Hate #1 — Submitting Forms on Keypress


This is the first entry in a series of things that annoy me. I don’t have exact goal of what these will be about but they will probably end up focusing on the web.

Submitting forms using the keypress event.

Dynamic sites, with less page reloads are awesome. The site I am developing is one page where the whole content is rendered using javascript. This helps reduce load time (after the initial) as well as separates permissions (all data has to come through the API) from display. However you still need to use elements how they were meant to be used. For example, to get users input some sites use code similar to the following.

	Please type something: <input id="in" type="text"/>
<p id="sub" style="background-color:red;display:none">AHHH I POPPED UP!</p>
	document.getElementById("in").addEventListener("keypress", function(e){
		if ( e.keyCode == 13 ) // The enter key code.
			document.getElementById("sub").style.display = "block";
	}, false);

What is wrong?

Looks fine doesn’t it? WRONG! What happens if the user-agent decides to auto-complete the form? Useful right? But now when the user accepts the suggestion (with the enter key) your callback runs and sends to user to a failure page (because they haven’t completed the rest of the form). Worse, this often happens before the auto-completed text gets put in the field (depending on which event you listen for). I don’t know how many times I have sent “kev” to a site because I was trying to auto-complete my email address.

This is also forcing your user to use the key you have decided should be used to submit forms, what if they use ‘q’ to submit forms. There is no reason the enter key should be used. A real life example is people who don’t use a traditional web browser. They may use their voice, and hitting the enter key to satisfy your form may be weird to impossible.

How do we fix it?

It is very simple. Use a form. This is a really cool element designed to let a user submit information, including auto-completion and DOING WHAT THEY EXPECT! The code is proper like this.

<p><form id="f">
	Please type something: <input type="text"/>
<p id="sub" style="background-color:red;display:none">
	I popped up when you wanted me to.
	document.getElementById("f").addEventListener("submit", function(e) {
		document.getElementById("sub").style.display = "block";
	}, false);

Simple, now the form is submitted when the user-agent feels that the user meant to submit it (which will be a way better guess then you can ever make). Now you can stop annoying your users (or at least me) by submitting uncompleted forms for them.

Feed - Newsletter - Private Feedback