Prevent Enter Key Submitting Forms With JQuery

15th July 2011

A common practice that some users have is to press the enter key when they are filling in forms on the web. This might be when they are just moving to the next field, but the trouble is that this will submit the form.

To prevent this from happening you can simply stop the form being submitted if the enter key had been pressed. This is done by binding a JQuery event to the input elements of the form and returning false if the key pressed is enter, which has the keyCode value of 13. We also include a call to the JQuery method preventDefault() to stop the event propagating.

  1. $('form input').keydown(function (e) {
  2. if (e.keyCode == 13) {
  3. e.preventDefault();
  4. return false;
  5. }
  6. });

Taking this a step further it might be an idea to try and achieve what the users are expecting and jump the focus to the next element in the form. Due to security restrictions it is impossible to change the key that was pressed to a tab, but the event we are looking for can be easily simulated. All we need to do it find all the input elements in the form, figure out where the current element is and then focus on the next input element (if it exists). The following code does just this.

  1. $('form input').keydown(function (e) {
  2. if (e.keyCode == 13) {
  3. var inputs = $(this).parents("form").eq(0).find(":input");
  4. if (inputs[inputs.index(this) + 1] != null) {
  5. inputs[inputs.index(this) + 1].focus();
  6. }
  7. e.preventDefault();
  8. return false;
  9. }
  10. });

Comments

Permalink

You are going to stop people also from pressing Enter on "Submit"?

Change:

$('form input').keydown(function (e) {

to:

$('form input:not([type="submit"])').keydown(function(e) {

Azizur Rahman (Mon, 07/18/2011 - 11:30)

Permalink

thanks for the code , it help me alot, thanks again

Israel R (Fri, 01/06/2012 - 20:24)

Permalink

I can submit this form bt pressing teh Enter key when in a text input field (i.e if I use the Enter key instead of the tab key to move from one field to the next. I tried to prevent this on my site using teh Jquery on this page but it did not work for me either. Is there a better way ?

Chhers

Richard

Anonymous (Wed, 02/22/2012 - 21:29)

Permalink
I'm starting with jquery and this article has helped me a lot. Thank you for writing it.

Django developer (Fri, 11/03/2017 - 10:09)

Permalink

Awesome :)

Paritosh Singh (Fri, 09/27/2019 - 19:40)

Add new comment

The content of this field is kept private and will not be shown publicly.