976

I have a survey on a website, and there seems to be some issues with the users hitting enter (I don't know why) and accidentally submitting the survey (form) without clicking the submit button. Is there a way to prevent this?

I'm using HTML, PHP 5.2.9, and jQuery on the survey.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
DForck42
  • 19,789
  • 13
  • 59
  • 84
  • 3
    Don't use form tags and do custom ajax request :) But sure, you can go ahead with the key-listening and prevention approach, that's what I'd do.. – jancha Jun 16 '16 at 07:43
  • I just don't use the form tags because I prefer to process forms through ajax requests by non-conventional ways (i.e: submitting some fields as their focus are dropped, etc). You can also make a special listener to catch Enter key and process it only if you want to do it. – Juan Aug 28 '17 at 16:49

36 Answers36

1035

You can use a method such as

$(document).ready(function() {
  $(window).keydown(function(event){
    if(event.keyCode == 13) {
      event.preventDefault();
      return false;
    }
  });
});

In reading the comments on the original post, to make it more usable and allow people to press Enter if they have completed all the fields:

function validationFunction() {
  $('input').each(function() {
    ...

  }
  if(good) {
    return true;
  }
  return false;
}

$(document).ready(function() {
  $(window).keydown(function(event){
    if( (event.keyCode == 13) && (validationFunction() == false) ) {
      event.preventDefault();
      return false;
    }
  });
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 9
    I'm currently just looking for a quick fix, and don't have time to implement validation items. I appreciate everyone's answers, but this is the one i'm going to go with in the mean time. thank you. – DForck42 May 22 '09 at 13:42
  • Hi @Simon_Weaver and @Phil-carter - My code happens in a switch case statement $searchBox.keyup(function (event) `switch (event.keyCode){ case 13: event.preventDefault(); return false; break;` ... then there's a bunch of other key codes being checked. In my case, this solution is not working at all. Any ideas **why**? – Jacques Mar 11 '11 at 08:04
  • 11
    This method is unideal because it prevents the user from submitting the form by pressing enter while focused on the submit button. The best solution would be that of BalusC below, where enter is interrupted only while still focused on the form inputs. – Anson Kao Oct 19 '11 at 17:25
  • 3
    I've seen situations (Internet Explorer only) where you need to bind to `keydown` on the `document` instead of the `window` for this to work. – MartinHN Feb 22 '12 at 09:03
  • 18
    You might want to add `&& !$(document.activeElement).is('textarea')` to the condition, or else newlines inside a textarea are blocked (in IE at least). – Flash Aug 08 '12 at 06:47
  • This works in chrome but not in IE8 for me. The top answer here worked for me: http://stackoverflow.com/questions/585396/how-to-prevent-enter-keypress-to-submit-a-web-form – Sam Watkins Feb 05 '14 at 00:38
  • Why to use `event.preventDefault();` if we could just use `return false;`? – Ankit Jan 02 '16 at 18:17
  • I can't make this work in Chrome. It looks like the events are not fired if the ENTER is pressed with the focus on a control inside a form. – Bruno Feb 26 '16 at 21:09
  • If you need to deal with textarea, then have a look to BalusC answer, it has better explaination – foobar Apr 13 '16 at 09:45
  • Can someone explain to me why event.keyCode == 13? Is that specific number necessary or are there other options for this? Thank you for your time. – Rookie Recruits Sep 22 '17 at 19:53
  • LIke others mentioned, I woudn't recommend this. At least attach it to a form. This prevents enter from being registered in Javascript. Technically it's not wrong.. – png Oct 02 '18 at 18:43
  • this is not a good solution, you don't want to prevent all enters, only submit – user151496 Feb 19 '19 at 15:21
  • 4
    This works for me. But this also prevent to add break line in textarea. – César León Feb 28 '19 at 15:09
  • Very nice solution to stop in whole system with few lines. Lovely. :) But it has stopped the ENTER key in textarea as well. We should allow that somehow. – Umar Niazi Jan 09 '20 at 10:56
  • Event.keyCode is [deprecated](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode); instead, you should use [event.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key). This also lets you removes the magic integer 13--`if (event.key == "Enter") ...` – Jack Brounstein Feb 12 '20 at 15:56
  • Below is a much easier and safer solution that does not the unintended side effect (ENTER on submit button does not work): https://stackoverflow.com/questions/895171/prevent-users-from-submitting-a-form-by-hitting-enter/51507806#51507806 – Weidenrinde Aug 27 '20 at 14:28
  • Oldie but goodie. Cannot count how many other solutions did not work for me. – Woody Jul 09 '21 at 17:22
805

Disallow enter key anywhere

If you don't have a <textarea> in your form, then just add the following to your <form>:

<form ... onkeydown="return event.key != 'Enter';">

Or with jQuery:

$(document).on("keydown", "form", function(event) { 
    return event.key != "Enter";
});

This will cause that every key press inside the form will be checked on the key. If it is not Enter, then it will return true and anything continue as usual. If it is Enter, then it will return false and anything will stop immediately, so the form won't be submitted.

The keydown event is preferred over keyup as the keyup is too late to block form submit. Historically there was also the keypress, but this is deprecated, as is the KeyboardEvent.keyCode. You should use KeyboardEvent.key instead which returns the name of the key being pressed. When Enter is checked, then this would check 13 (normal enter) as well as 108 (numpad enter).

Note that $(window) as suggested in some other answers instead of $(document) doesn't work for keydown/keyup in IE<=8, so that's not a good choice if you're like to cover those poor users as well.

Allow enter key on textareas only

If you have a <textarea> in your form (which of course should accept the Enter key), then add the keydown handler to every individual input element which isn't a <textarea>.

<input ... onkeydown="return event.key != 'Enter';">
<select ... onkeydown="return event.key != 'Enter';">
...

To reduce boilerplate, this is better to be done with jQuery:

$(document).on("keydown", ":input:not(textarea)", function(event) {
    return event.key != "Enter";
});

If you have other event handler functions attached on those input elements, which you'd also like to invoke on enter key for some reason, then only prevent event's default behavior instead of returning false, so it can properly propagate to other handlers.

$(document).on("keydown", ":input:not(textarea)", function(event) {
    if (event.key == "Enter") {
        event.preventDefault();
    }
});

Allow enter key on textareas and submit buttons only

If you'd like to allow enter key on submit buttons <input|button type="submit"> too, then you can always refine the selector as below.

$(document).on("keydown", ":input:not(textarea):not(:submit)", function(event) {
    // ...
});

Note that input[type=text] as suggested in some other answers doesn't cover those HTML5 non-text inputs, so that's not a good selector.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • This prevents enter key from working on any input other than textarea. It's not a good solution – mate.gvo Dec 02 '17 at 14:07
  • 3
    This should be the correct answer since it does not interfere with other enter key listeners. Ones like Bootstrap tags input: https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/ – Maroun Melhem Dec 11 '18 at 12:19
  • 1
    I chose this solution because it wasn't even a full line of code I had to add. All things held equal, shorter answers are better. – Jonathon Philip Chambers Jan 19 '19 at 12:51
  • Below is a much easier solution: https://stackoverflow.com/questions/895171/prevent-users-from-submitting-a-form-by-hitting-enter/51507806#51507806 – Weidenrinde Aug 27 '20 at 14:28
  • THIS answer is how someone becomes a SO "millionaire" – jpw Aug 29 '20 at 17:41
  • I don't like this answer because it does not shoot at the heart of the problem. It does not even understand the problem. This is a blind fix meaning if you don't understand the root cause, it will strike you back. I prefer Daniel Trebien's answer below for the root case analysis and lighter solution. – Philippe F Aug 04 '22 at 14:23
  • Great answer! However I am suggesting selector to be `':input:not(textarea):not(:button):not(:submit):not(:reset):not(:image):not(:file)'` to allow ENTER key pressed on other buttons and controls where ENTER key is a valid key. – Gyrocode.com Feb 13 '23 at 19:46
286

Section 4.10.22.2 Implicit submission of the W3C HTML5 spec says:

A form element's default button is the first submit button in tree order whose form owner is that form element.

If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.

Note: Consequently, if the default button is disabled, the form is not submitted when such an implicit submission mechanism is used. (A button has no activation behavior when disabled.)

Therefore, a standards-compliant way to disable any implicit submission of the form is to place a disabled submit button as the first submit button in the form:

<form action="...">
  <!-- Prevent implicit submission of the form -->
  <button type="submit" disabled style="display: none" aria-hidden="true"></button>

  <!-- ... -->

  <button type="submit">Submit</button>
</form>

One nice feature of this approach is that it works without JavaScript; whether or not JavaScript is enabled, a standards-conforming web browser is required to prevent implicit form submission.

Daniel Trebbien
  • 38,421
  • 18
  • 121
  • 193
74

If you use a script to do the actual submit, then you can add "return false" line to the onsubmit handler like this:

<form onsubmit="return false;">

Calling submit() on the form from JavaScript will not trigger the event.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tom Hubbard
  • 15,820
  • 14
  • 59
  • 86
  • Works for me in Chrome, this will also disable submit buttons, which is fine if you want to trigger an onlick-event on the submit button itself. Ajax hint: Add your function call before the return and the user can still hit the enter key without submitting the form to the page. – Dennis Heiden Aug 04 '16 at 15:08
  • Worked for me on Chrome, IE-11, and Firefox and was the simplest solution to implement. Disabling the enter key on whole sections of the page, as some answers do, seems too extreme and prone to bugs. – Yogi Apr 23 '18 at 15:49
70

I had to catch all three events related to pressing keys in order to prevent the form from being submitted:

    var preventSubmit = function(event) {
        if(event.keyCode == 13) {
            console.log("caught ya!");
            event.preventDefault();
            //event.stopPropagation();
            return false;
        }
    }
    $("#search").keypress(preventSubmit);
    $("#search").keydown(preventSubmit);
    $("#search").keyup(preventSubmit);

You can combine all the above into a nice compact version:

    $('#search').bind('keypress keydown keyup', function(e){
       if(e.keyCode == 13) { e.preventDefault(); }
    });
Upgradingdave
  • 12,916
  • 10
  • 62
  • 72
  • 7
    You could either chain the last 3 selectors or bind multiple events with one method like so `$("#search").bind('keypress keyup keydown',preventSubmit)`; – Moak Jan 03 '13 at 02:38
  • Because in an ASP.NET web form everything has to be nested in a `
    ` tag, the enter key *will* submit the form... This solution disabled the enter key and fixed the problem though, thanks @Dave! Then I enabled the enter key for certain fields by `id`.
    – Ian Campbell Aug 09 '13 at 18:23
  • @Upgradingdave How are you able to write "log()" instead of "console.log()"? – radbyx Sep 20 '18 at 05:51
  • 1
    @radbyx ... good catch, it should be `console.log`, I updated my answer. – Upgradingdave Sep 20 '18 at 14:52
  • Note that with `keypress keyup keydown` you trigger any code in the if condition *twice*. – Avatar Oct 31 '19 at 17:53
24

Use:

$(document).on('keyup keypress', 'form input[type="text"]', function(e) {
  if(e.keyCode == 13) {
    e.preventDefault();
    return false;
  }
});

This solution works on all forms on a website (also on forms inserted with Ajax), preventing only Enters in input texts. Place it in a document ready function, and forget this problem for a life.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Buzogany Laszlo
  • 921
  • 11
  • 19
  • I think the original answer `e.which` was fine; no need to change it to `e.keyCode`. Both return the value 13 for the enter key. See http://stackoverflow.com/a/4471635/292060 and http://stackoverflow.com/a/18184976/292060 – goodeye Sep 14 '14 at 16:23
  • 2
    This solution takes care of two solutions : 1.) Don't submit forms on enter 2.) Allows enter in the textareas – PlanetUnknown Apr 15 '16 at 20:33
22

I can't comment yet, so I'll post a new answer

Accepted answer is ok-ish, but it wasn't stopping submit on numpad enter. At least in current version of Chrome. I had to alter the keycode condition to this, then it works.

if(event.keyCode == 13 || event.keyCode == 169) {...}
ono2012
  • 4,967
  • 2
  • 33
  • 42
sparklos
  • 452
  • 4
  • 10
22

A completely different approach:

  1. The first <button type="submit"> in the form will be activated on pressing Enter.
  2. This is true even if the button is hidden with style="display:none;
  3. The script for that button can return false, which aborts the submission process.
  4. You can still have another <button type=submit> to submit the form. Just return true to cascade the submission.
  5. Pressing Enter while the real submit button is focussed will activate the real submit button.
  6. Pressing Enter inside <textarea> or other form controls will behave as normal.
  7. Pressing Enter inside <input> form controls will trigger the first <button type=submit>, which returns false, and thus nothing happens.

Thus:

<form action="...">
  <!-- insert this next line immediately after the <form> opening tag -->
  <button type=submit onclick="return false;" style="display:none;"></button>

  <!-- everything else follows as normal -->
  <!-- ... -->
  <button type=submit>Submit</button>
</form>
Erics
  • 803
  • 9
  • 23
  • 1
    Hmm, in Chrome and Firefox, an even shorter version would be – Erics Feb 27 '17 at 05:12
  • 1
    I really don't liked the "ignoring 13 keycode" way, so i started to thinking for some easy and tricky way, and this idea came to my mind and as i was scrolling down this page i saw this thread :). Plus one for mutual idea and of-course the best solution. – Jalali Shakib May 10 '18 at 05:42
  • Perfect answer for me. I wanted a form to emulate a CLI so the user would press enter for each next field and then have a submit at the end. – nathan Jul 08 '18 at 20:22
  • oh brilliant , the last button can be like this to prevent duplication submit on rapid clicks : `` – Arash Oct 06 '19 at 12:57
  • @ArashMoosapour please don't disable submit buttons if they have focus - doing so drops focus and is a mess for accessibility. – Erics Oct 07 '19 at 20:45
  • This is brilliant. Simple, uses the specs. – logicOnAbstractions Nov 10 '21 at 19:53
  • I don't see any effect of this hidden button in my Firefox – Роман Коптев Mar 02 '23 at 10:38
22

Instead of preventing users from pressing Enter, which may seem unnatural, you can leave the form as is and add some extra client-side validation: When the survey is not finished the result is not sent to the server and the user gets a nice message telling what needs to be finished to complete the form. If you are using jQuery, try the Validation plugin:

http://docs.jquery.com/Plugins/Validation

This will require more work than catching the Enter button, but surely it will provide a richer user experience.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
bbmud
  • 2,678
  • 21
  • 15
  • 16
    This sounds good but optional fields are problematic, the user may press enter by mistake and the form will be submitted. I do not see how you are going to know when the _survey is not finished_ unless you put every field as required (no default choices, no blank fields allowed...) – Christophe Roussy Jan 30 '13 at 11:00
21

A nice simple little jQuery solution:

$("form").bind("keypress", function (e) {
    if (e.keyCode == 13) {
        return false;
    }
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eonasdan
  • 7,563
  • 8
  • 55
  • 82
  • 1
    +1 I was looking for a jQuery alternative, instead of using normal JS like `var key = event.keyCode || event.which; if (key == 13) return false;` – RaphaelDDL Dec 13 '11 at 13:38
  • 1
    technically this is still POJ just with a simpler jquery wrapper. the code that you've given is nearly the same thing. – Eonasdan Dec 13 '11 at 14:03
18

It is my solution to reach the goal, it is clean and effective.

$('form').submit(function () {
  if ($(document.activeElement).attr('type') == 'submit')
     return true;
  else return false;
});
Developer
  • 788
  • 6
  • 10
13

Not putting a submit button could do. Just put a script to the input (type=button) or add eventListener if you want it to submit the data in the form.

Rather use this

<input type="button" onclick="event.preventDefault();this.closest('form').submit();">

than using this

<input type="submit">

Note: onclick is needed here to actually submit the form when clicked. By default, type="button" is not sufficient enough to submit.

cevaris
  • 5,671
  • 2
  • 49
  • 34
Jimwel Anobong
  • 468
  • 5
  • 18
12

You can also use javascript:void(0) to prevent form submission.

<form action="javascript:void(0)" method="post">
    <label for="">Search</label>
    <input type="text">
    <button type="sybmit">Submit</button>
</form>

<form action="javascript:void(0)" method="post">
    <label for="">Search</label>
    <input type="text">
    <button type="sybmit">Submit</button>
</form>
Nisharg Shah
  • 16,638
  • 10
  • 62
  • 73
  • does not work when you specifically have `method="post"` on your form. For instance I want the form to be submitted by buttons, but not when pressing enter while focused in the input. – Souleste Nov 14 '19 at 22:16
  • for that condition you can use above answers because this answer is based on prevent form submission by enter and click both. above example have `method="post"` in form and its works, check again. – Nisharg Shah Nov 15 '19 at 04:41
9

Giving the form an action of 'javascript:void(0);' seems to do the trick

<form action="javascript:void(0);">
<input type="text" />
</form>
<script>
$(document).ready(function() {
    $(window).keydown(function(event){
        if(event.keyCode == 13) {
    alert('Hello');
        }
    });
});
</script>
sidarcy
  • 2,958
  • 2
  • 36
  • 37
8
  1. Do not use type="submit" for inputs or buttons.
  2. Use type="button" and use js [Jquery/angular/etc] to submit form to server.
Irfan Ashraf
  • 2,430
  • 21
  • 20
8

This is the perfect way, You will not be redirected from your page

$('form input').keydown(function (e) {
if (e.keyCode == 13) {
    e.preventDefault();
    return false;
}
});
Khn Rzk
  • 1,124
  • 2
  • 15
  • 26
7

I needed to prevent only specific inputs from submitting, so I used a class selector, to let this be a "global" feature wherever I need it.

<input id="txtEmail" name="txtEmail" class="idNoEnter" .... />

And this jQuery code:

$('.idNoEnter').keydown(function (e) {
  if (e.keyCode == 13) {
    e.preventDefault();
  }
});

Alternatively, if keydown is insufficient:

$('.idNoEnter').on('keypress keydown keyup', function (e) {
   if (e.keyCode == 13) {
     e.preventDefault();
   }
});

Some notes:

Modifying various good answers here, the Enter key seems to work for keydown on all the browsers. For the alternative, I updated bind() to the on() method.

I'm a big fan of class selectors, weighing all the pros and cons and performance discussions. My naming convention is 'idSomething' to indicate jQuery is using it as an id, to separate it from CSS styling.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
goodeye
  • 2,389
  • 6
  • 35
  • 68
  • This works on the textbox elements in the form. As you type, and hit enter in the textbox, the default behavior submits the form. This intercepts the enter key and prevents it from submitting. – goodeye Jun 01 '14 at 21:37
6

There are many good answers here already, I just want to contribute something from a UX perspective. Keyboard controls in forms are very important.

The question is how to disable from submission on keypress Enter. Not how to ignore Enter in an entire application. So consider attaching the handler to a form element, not the window.

Disabling Enter for form submission should still allow the following:

  1. Form submission via Enter when submit button is focused.
  2. Form submission when all fields are populated.
  3. Interaction with non-submit buttons via Enter.

This is just boilerplate but it follows all three conditions.

$('form').on('keypress', function(e) {
  // Register keypress on buttons.
  $attr = $(e.target).attr('type');
  $node = e.target.nodeName.toLowerCase();
  if ($attr === 'button' || $attr === 'submit' || $node === 'textarea') {
    return true;
  }

  // Ignore keypress if all fields are not populated.
  if (e.which === 13 && !fieldsArePopulated(this)) {
    return false;
  }
});
NaN
  • 8,596
  • 20
  • 79
  • 153
png
  • 1,130
  • 14
  • 18
  • 1
    Missing the conditional for `textarea` fields. The way it is, it's not creating new lines in `textarea` fields. – NaN Oct 20 '21 at 11:43
  • 1
    I believe this should be selected as the right answer! – NaN Oct 20 '21 at 11:47
6

You could make a JavaScript method to check to see if the Enter key was hit, and if it is, to stop the submit.

<script type="text/javascript">
  function noenter() {
  return !(window.event && window.event.keyCode == 13); }
</script>

Just call that on the submit method.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Brandon
  • 68,708
  • 30
  • 194
  • 223
5

ONLY BLOCK SUBMIT but not other, important functionality of enter key, such as creating a new paragraph in a <textarea>:

window.addEventListener('keydown', function(event) {
  //set default value for variable that will hold the status of keypress
  pressedEnter = false;

  //if user pressed enter, set the variable to true
  if (event.keyCode == 13)
    pressedEnter = true;

  //we want forms to disable submit for a tenth of a second only
  setTimeout(function() {
    pressedEnter = false;
  }, 100)

})

//find all forms
var forms = document.getElementsByTagName('form')

//loop through forms
for (i = 0; i < forms.length; i++) {
  //listen to submit event
  forms[i].addEventListener('submit', function(e) {
    //if user just pressed enter, stop the submit event
    if (pressedEnter == true) {
      updateLog('Form prevented from submit.')
      e.preventDefault();
      return false;
    }

    updateLog('Form submitted.')
  })
}

var log = document.getElementById('log')
updateLog = function(msg) {
  log.innerText = msg
}
input,
textarea {
  display: inline-block;
  margin-bottom: 1em;
  border: 1px solid #6f6f6f;
  padding: 5px;
  border-radius: 2px;
  width: 90%;
  font-size: 14px;
}

input[type=submit] {
  background: lightblue;
  color: #fff;
}
<form>
  <p>Sample textarea (try enter key):</p>
  <textarea rows="4">Hit enter, a new line will be added. But the form won't submit</textarea><br/>
  <p>Sample textfield (try enter key):</p>
  <input type="text" placeholder="" />
  <br/>
  <input type="submit" value="Save" />
  <h3 id="log"></h3>
</form>
mate.gvo
  • 1,093
  • 14
  • 20
  • wondering who and why would downvote this :| what's the issue with my solution? – mate.gvo Sep 28 '18 at 13:54
  • Upvoted for the contribution. The accepted answer breaks most form UI, preventing "enter" from being registered on the entire application. Not good. I think it's a good idea to allow enter to be handled in form elements, particularly buttons so I like the path you're going down. I think this can be achieved without a timeout though. For example just look at the element attribute in your event handler. Allow 'button' and 'submit' – png Oct 02 '18 at 20:15
  • @NathanCH - This code does exactly the opposite from what you're saying. It *only prevents enter from submitting the form* and doesn't prevent any other functionality - for example, you might have a text field and want to use enter to create new paragraphs. – mate.gvo Oct 03 '18 at 21:07
  • 1
    There's a typo in the first line. Instead of `function(e)` it should be `function(event)`. Otherwise, it works for me. Thank you. – Guillermo Prandi Nov 30 '18 at 17:05
  • @GuillermoPrandi thank you! That explains why the solution got some downvotes – mate.gvo Dec 01 '18 at 18:10
  • why is `setTimeout(function() { pressedEnter = false; }, 100)` not inside the `event.keyCode == 13` condition? – user151496 Feb 19 '19 at 15:26
  • 2
    This is an absolute lifesaver, since everything else prevents me from properly handling enter save events for things like grid inline edits. The only suggestion is to not use 'setTimeout' at all. I think that's the problem people have with this answer. It's too finicky. Instead, for the event do `on("keydown", function(event) { enterPressed = true; }` and then in the submit event, do `on("submit", function(e) { if (pressedEnter == true) { pressedEnter = false; e.preventDefault(); return false;}` This will ensure that it works no matter the delay. – Curtis Snowden Feb 06 '20 at 23:08
5

I have use this Code to disable 'ENTER' key press on both input type [text] and input type [password], you can add other too like input type [email] or also can apply on your desired Input type.

$(document).on('keyup keypress', 'form input[type="text"] , input[type="password"]', function(e) {
        if (e.keyCode == 13) {
            e.preventDefault();
            return false;
        }
    });
M Ali Imtiaz
  • 145
  • 2
  • 5
5

If you're using Alpine, you can use the following to prevent form submission by pressing Enter:

<div x-data>
  <form x-on:keydown.prevent.enter="">...</form>
</div>

Alternatively you can use the .window modifier to register the event listener on the root window object on the page instead of the element.

<form>
  <div x-data>
    <input x-on:keydown.window.prevent.enter="" type="text">
  </div>
</form>
bdoubleu
  • 5,568
  • 2
  • 20
  • 53
3
$(document).on("keydown","form", function(event)
{
   node = event.target.nodeName.toLowerCase();
   type = $(event.target).prop('type').toLowerCase();

   if(node!='textarea' && type!='submit' && (event.keyCode == 13 || event.keyCode == 169))
   {
        event.preventDefault();
        return false;
    }
});

It works perfectly!

Stergios Zg.
  • 652
  • 6
  • 9
3

If using Vue, use the following code to prevent users from submitting the form by hitting Enter:

<form @submit.prevent>...</form>
Wenfang Du
  • 8,804
  • 9
  • 59
  • 90
2

I had a similiar problem, where I had a grid with "ajax textfields" (Yii CGridView) and just one submit button. Everytime I did a search on a textfield and hit enter the form submitted. I had to do something with the button because it was the only common button between the views (MVC pattern). All I had to do was remove type="submit" and put onclick="document.forms[0].submit()

StackUnder
  • 252
  • 8
  • 18
2

I think it's well covered with all the answers, but if you are using a button with some JavaScript validation code you could just set the form's onkeypress for Enter to call your submit as expected:

<form method="POST" action="..." onkeypress="if(event.keyCode == 13) mySubmitFunction(this); return false;">

The onkeypress JS could be whatever you need to do. There's no need for a larger, global change. This is especially true if you're not the one coding the app from scratch, and you've been brought into fix someone else's web site without tearing it apart and re-testing it.

dubmojo
  • 6,660
  • 8
  • 41
  • 68
  • I realize its a variant on Tom Hubbard's answer, which I +1'd because its actually what I did myself today before searching SO for other ideas. – dubmojo Jul 28 '13 at 17:58
1

Something I have not seen answered here: when you tab through the elements on the page, pressing Enter when you get to the submit button will trigger the onsubmit handler on the form, but it will record the event as a MouseEvent. Here is my short solution to cover most bases:

This is not a jQuery-related answer

HTML

<form onsubmit="return false;" method=post>
  <input type="text" /><br />
  <input type="button" onclick="this.form.submit()" value="submit via mouse or keyboard" />
  <input type="button" onclick="submitMouseOnly(event)" value="submit via mouse only" />
</form>

JavaScript

window.submitMouseOnly=function(evt){
    let allow=(evt instanceof MouseEvent) && evt.x>0 && evt.y>0 && evt.screenX > 0 && evt.screenY > 0;
    if(allow)(evt.tagName=='FORM'?evt.target:evt.target.form).submit();
}

To find a working example: https://jsfiddle.net/nemesarial/6rhogva2/

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nemesarial
  • 487
  • 5
  • 12
1

Using Javascript (without checking any input field):

<script>
window.addEventListener('keydown', function(e) {
    if (e.keyIdentifier == 'U+000A' || e.keyIdentifier == 'Enter' || e.keyCode == 13) {
        e.preventDefault();
        return false;
    }
}, true);
</script>

If someone wants to apply this on specific fields, for example input type text:

<script>
window.addEventListener('keydown', function(e) {
    if (e.keyIdentifier == 'U+000A' || e.keyIdentifier == 'Enter' || e.keyCode == 13) {
        if (e.target.nodeName == 'INPUT' && e.target.type == 'text') {
            e.preventDefault();
            return false;
        }
    }
}, true);
</script>

This works well in my case.

Waqar Alamgir
  • 9,828
  • 4
  • 30
  • 36
1

Go into your css and add that to it then will automatically block the submission of your formular as long as you have submit input if you no longer want it you can delete it or type activate and deactivate instead

 input:disabled {
        background: gainsboro;
      }
      input[value]:disabled {
        color: whitesmoke;
      }
Lars Gross
  • 102
  • 6
1

This disables enter key for all the forms on the page and does not prevent enter in textarea.

    // disable form submit with enter

    $('form input:not([type="submit"])').keydown((e) => {
        if (e.keyCode === 13) {
            e.preventDefault();
            return false;
        }
        return true;
    });
David Dehghan
  • 22,159
  • 10
  • 107
  • 95
0

In my specific case I had to stop ENTER from submitting the form and also simulate the clicking of the submit button. This is because the submit button had a click handler on it because we were within a modal window (inherited old code). In any case here's my combo solutions for this case.

    $('input,select').keypress(function(event) {
        // detect ENTER key
        if (event.keyCode == 13) {
            // simulate submit button click
            $("#btn-submit").click();
            // stop form from submitting via ENTER key press
            event.preventDefault ? event.preventDefault() : event.returnValue = false;
        }
    });

This use case is specifically useful for people working with IE8.

Stone
  • 2,608
  • 26
  • 26
0

This works for me

jQuery.each($("#your_form_id").find('input'), function(){
    $(this).bind('keypress keydown keyup', function(e){
       if(e.keyCode == 13) { e.preventDefault(); }
    });
});
Pjl
  • 1,752
  • 18
  • 21
0

I'd like to add a little CoffeeScript code (not field tested):

$ ->
    $(window).bind 'keypress', (event) ->
        if event.keyCode == 13
            unless {'TEXTAREA', 'SELECT'}[event.originalEvent.srcElement.tagName]
                event.preventDefault()

(I hope you like the nice trick in the unless clause.)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
edx
  • 1,317
  • 1
  • 12
  • 14
-2

Use:

// Validate your form using the jQuery onsubmit function... It'll really work...

$(document).ready(function(){
   $(#form).submit(e){
       e.preventDefault();
       if(validation())
          document.form1.submit();
   });
});

function validation()
{
   // Your form checking goes here.
}

<form id='form1' method='POST' action=''>
    // Your form data
</form>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tapas Pal
  • 7,073
  • 8
  • 39
  • 86
-2

This has worked for me in all browsers after much frustration with other solutions. The name_space outer function is just to stay away from declaring globals, something I also recommend.

$(function() {window.name_space = new name_space();}); //jquery doc ready
function name_space() {
    this.is_ie = (navigator.userAgent.indexOf("MSIE") !== -1);

    this.stifle = function(event) {
        event.cancelBubble;
        event.returnValue = false;
        if(this.is_ie === false) {
            event.preventDefault();
        }
        return false;
    }

    this.on_enter = function(func) {
        function catch_key(e) {
            var enter = 13;
            if(!e) {
                var e = event;
            }
            keynum = GetKeyNum(e);
            if (keynum === enter) {
                if(func !== undefined && func !== null) {
                    func();
                }
                return name_space.stifle(e);
            }
            return true; // submit
        }

        if (window.Event) {
            window.captureEvents(Event.KEYDOWN);
            window.onkeydown = catch_key;
        }
        else {
            document.onkeydown = catch_key;
        }

        if(name_space.is_ie === false) {
            document.onkeypress = catch_key;    
        }
    }
}

Sample use:

$(function() {
    name_space.on_enter(
        function () {alert('hola!');}
    );
});
crizCraig
  • 8,487
  • 6
  • 54
  • 53
-3

In my case I had a couple of jQuery UI autocomplete fields and textareas in a form, so I definitely wanted them to accept Enter. So I removed the type="submit" input from a form and added an anchor <a href="" id="btn">Ok</a> instead. Then I styled it as a button and added the following code:

$( '#btn' ).click( function( event ){
    event.preventDefault();
    if ( validateData() ){
        $( 'form#frm' ).append( '<input type="submit" id="frm-submit" style="display:none;"></input>' );
        setTimeout( function(){ $( '#frm-submit' ).click(); }, 500 );
    }
    return false;
});

If a user fills all required fields, validateData() succeeds and the form submits.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Blza Box
  • 325
  • 3
  • 6