jQuery

How To Disable Enter Key On Forms

Enter key

On HTML forms if you are filling out a text box and press the enter key it will submit the form, even if you haven't finished filling in the rest of the information.

There are many websites which use this feature such as Google search box will submit when you press the enter key. This works because you only have one text box to fill out, but if there are more than one field to fill in you don't want the form to submit on the enter key.

To change this basic feature you need to add a bit of Javascript on the page to stop the form submitting. I use jQuery so the following snippet will show you how you can turn off the enter key using jQuery.

$("form").keypress(function(e) {
  //Enter key
  if (e.which == 13) {
    return false;
  }
});

This will check to see what key you have pressed if it is an enter key then the function will return false which will stop the form from submitting.

Back to top

Learn how to code with Treehouse

  • Learn projects with access to 1000+ videos
  • Practice live with our Code Challenge Engine
  • Get help in our members-only forums

Start with a 7 day free trial