Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Leandro Severino
Leandro Severino
12,674 Points

How to disable submitting a form when I press on the enter key?

I have a button in my form, the purpose is not to submit the form. When I press "enter" key, it behaves as if I submitted the form. I'd like the enter key to act as if I clicked a certain button which means it will call my custom function rather than submit the form. How can I do that? Thanks.

1 Answer

Hi Leandro,

Try something like this:

document.getElementById("YOURFORMNAMEHERE").onkeypress = function(e) {
  var key = e.charCode || e.keyCode || 0;     
  if (key == 13) {
    e.preventDefault();
  }
}

This will stop the enter key from submit. If you have a custom function you would like to trigger in there, you would have to put it after the preventDefault().