Prevent Early Form Submission by Hijacking the Enter Key

Written by David Walsh on Monday, October 13, 2008


This article may feature code that is no longer best practice in MooTools.
Click here to learn what has changed to make your code framework-compatible.

A customer asked me to create a timecard form a few years ago. Everything with the form worked great but users would mistakenly press the enter key before their form was completed. They asked that I make the enter key move the cursor to the next input instead of submitting the form. This is how I’d do that using MooTools javascript.

The MooTools Javascript

var inputs = $$('input.hijack');
$each(inputs,function(el,i) {
	el.addEvent('keypress',function(e) {
		if(e.key == 'enter') { 
			e.stop(); 
			if(inputs[i+1]) { inputs[i+1].focus(); }
			//last one?
			if(i == inputs.length-1) { $('submit-button').focus(); }
		}
	});
});

When the customer hits the enter key, the cursor simply appears in the next input.

While I certainly wouldn’t recommend this for every form, it definitely suited this customer’s needs.


Follow via RSS Epic Discussion

Commenter Avatar October 13 / #
Ahmed says:

Awesome!

Commenter Avatar October 14 / #
JGM says:

Outstanding little clip…one I can put into use almost immediately!

Commenter Avatar October 14 / #

Agreed! Excellent and well executed idea. As you say, probably not for all forms — and it might be useful to provide some education with respect to the tab key which is for all forms — but useful for critical processes that must not be interrupted. Well done.

Commenter Avatar January 07 / #

How about the TAB key?

Be Heard!

I want to hear what you have to say! Share your comments and questions below.

Name*:
Email*:
Website:  


© David Walsh 2007-2010. Contact David Walsh. Powered by the remarkable MooTools javascript framework.