Conditional Enter / Submit handling in HTML forms with JavaScript

The problem: if you press Enter key while inside a field of HTML form — the form will execute its submit action. Thus if your users are used to pressing return to move to the next field — they will be unpleasantly surprised. I'll show how this can be changed on example of a simple login form.

This will be a quick one, since the task is rather straightforward.

Let's assume a very simple HTML form structure:
<form>
    <input id="login" name="login" type="text" placeholder="Your login">
    <input id="password" name="password" type="password" placeholder="Your password">
    <button type="submit" id="submit">Submit</button>
</form>
If you don't do anything about it, pressing Enter key while in the Login input field will invoke the Submit action. Not good.

To demonstrate it I'll add an alert on submit action (using jQuery for readability in this case), this will help us see clearly when it is actually being invoked:
$('form').submit(function() { 
    alert('Submit!'); 
});
For this study let's concentrate on just the Login field. If you want to stop submit from being invoked on an empty Password field you can apply the same principle.

The code:
$('#login').on('keydown', function (e) {
    if (e.keyCode == 13) {
        // Move to password field if login not empty
        if($('#login').val() !== '')
            $('#password').focus();
        
        // Stop submit from being invoked
        e.preventDefault();
    }
});

The following is happening above:
  • keydown even is being overridden for the login field.
  • In the event handler we check for key code 13, which corresponds to Enter key press.
  • If the login field is not empty (val() is not an empty string) — then move the cursor (with .focus() method) to the password field.
  • preventDefault() is called on the event to, er, prevent it from executing the default action. In our case, the default action on pressing Enter is to submit the form, so this action is being prevented. Just what we need!
Here's the corresponding demo fiddle. You can comment out the keydown event override to see how Submit is called without it.

I hope this helps, and take care!

PS I do need to spend some time getting away from reliance on jQuery — it is one of my (plenty) weaknesses. I plan to do some studying this week, yet it is so easy to demonstrate event handling etc using it, so I think I'll keep using it in my code examples, except for when pure JavaScript is easier to understand.

Comments

  1. Thank you for the post. And are there any tricks to counter the problem in case Javascript is turned off?

    ReplyDelete
    Replies
    1. Mmmm, I can't see any way out of this. Is there? If there was such a solution, all of the above would be unnecessary, heh. So let me know if you do.

      On the bright side, this degrades gracefully unless you override form submit with your code — you can still use the form as standard HTML, move between fields with Tab etc.

      On even brighter side, almost all of my projects now are webapps, so not having JS will make them completely unusable. Thus I can require and rely on users having it on.

      Delete
    2. I don't know solution to your "Enter to move between fields" problem. All I know are HTML5 features like <input required/> and such. For example described with pictures here http://diveintohtml5.info/forms.html (w3c specs are dull and convoluted - it's always better to read illustrated ones with good typography, right? :))

      Delete
    3. Yep, didn't see a suitable alternative there… thanks for the link though, I read it a while ago, but good to skim it over now too, to refresh vague memories :)

      Delete

Post a Comment

Popular Posts