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
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

  • By
    Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven...

Incredible Demos

  • By
    Introducing MooTools HeatMap

    It's often interesting to think about where on a given element, whether it be the page, an image, or a static DIV, your users are clicking.  With that curiosity in mind, I've created HeatMap: a MooTools class that allows you to detect, load, save, and...

  • By
    Create a Simple News Scroller Using Dojo

    My journey into Dojo JavaScript has been exciting and I'm continuing to learn more as I port MooTools scripts to Dojo. My latest experiment is porting a simple new scroller from MooTools to Dojo. The code is very similar! The HTML The news items...

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!