Prevent Early Form Submission by Hijacking the Enter Key

By  on  

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.

Recent Features

  • By
    LightFace:  Facebook Lightbox for MooTools

    One of the web components I've always loved has been Facebook's modal dialog.  This "lightbox" isn't like others:  no dark overlay, no obnoxious animating to size, and it doesn't try to do "too much."  With Facebook's dialog in mind, I've created LightFace:  a Facebook lightbox...

  • By
    5 HTML5 APIs You Didn’t Know Existed

    When you say or read "HTML5", you half expect exotic dancers and unicorns to walk into the room to the tune of "I'm Sexy and I Know It."  Can you blame us though?  We watched the fundamental APIs stagnate for so long that a basic feature...

Incredible Demos

  • By
    Ana Tudor’s Favorite CodePen Demos

    Cocoon I love canvas, I love interactive demos and I don't think I have ever been more impressed by somebody's work than when I discovered what Tiffany Rayside has created on CodePen. So I had to start off with one of her interactive canvas pens, even though...

  • By
    MooTools Window Object Dumping

    Ever want to see all of the information stored within the window property of your browser? Here's your chance. The XHTML We need a wrapper DIV that we'll consider a console. The CSS I like making this look like a command-line console. The MooTools JavaScript Depending on what you have loaded...

Discussion

  1. Ahmed

    Awesome!

  2. JGM

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

  3. 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.

  4. How about the TAB key?

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!