80

I have been trying to disable the Enter key on my form. The code that I have is shown below. For some reason the enter key is still triggering the submit. The code is in my head section and seems to be correct from other sources.

disableEnterKey: function disableEnterKey(e){
        var key;      
        if(window.event)
            key = window.event.keyCode; //IE
        else
            key = e.which; //firefox      

        return (key != 13);
    },
Chris Pinski
  • 4,493
  • 3
  • 22
  • 16
  • Are you attaching this to the form, the submit button, or the window? – cwharris Apr 12 '11 at 02:42
  • So you're giving us code that you know works... and asking why it's not? P.S. [This fiddle](http://jsfiddle.net/Khez/E9L57/) proves it works, so try giving more data on your issue. Does the function even run ? – Khez Apr 12 '11 at 02:46

16 Answers16

135

if you use jQuery, its quite simple. Here you go

$(document).keypress(
  function(event){
    if (event.which == '13') {
      event.preventDefault();
    }
});
Tim
  • 1,045
  • 14
  • 23
Steven Jiang
  • 1,390
  • 1
  • 8
  • 5
  • 3
    That works, but if you need to disable it in a specific area od your code? Example: you want to disable enter in a form, but to be avaliable in the seeker in the top nav bar. – ManelPNavarro Feb 20 '14 at 16:08
  • 2
    Selector could be anything you want it to be. The $(document) is the selector. You can have $("#IDofYourElement") that will select any element that has id="IDofYourElement". Learn JQuery selectors so you easily visualize what is going on. Else you will continue asking this sort of questions along with "How to select a div tag? How to select a section?". Learning the rules and applying it is the key here. – Alexey Shevelyov Jun 01 '16 at 20:34
  • this works well, on a .net page with multiple (asp.net) buttons, enter somehow triggers the wrong function, this now stabilizes the page, thanks! – visual Aug 04 '17 at 01:48
  • Just a tidbit - but you can use an arrow function too.. $(document.keypress((event)=>{ if (event.which == '13') { event.preventDefault(); } }); – jpgerb Dec 13 '22 at 19:47
63

Most of the answers are in jquery. You can do this perfectly in pure Javascript, simple and no library required. Here it is:

<script type="text/javascript">
    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 code works great because, it only disables the "Enter" keypress action for input type='text'. This means visitors are still able to use "Enter" key in textarea and across all of the web page. They will still be able to submit the form by going to the "Submit" button with "Tab" keys and hitting "Enter".

Here are some highlights:

  1. It is in pure javascript (no library required).
  2. Not only it checks the key pressed, it confirms if the "Enter" is hit on the input type='text' form element. (Which causes the most faulty form submits
  3. Together with the above, user can use "Enter" key anywhere else.
  4. It is short, clean, fast and straight to the point.

If you want to disable "Enter" for other actions as well, you can add console.log(e); for your your test purposes, and hit F12 in chrome, go to "console" tab and hit "backspace" on the page and look inside it to see what values are returned, then you can target all of those parameters to further enhance the code above to suit your needs for "e.target.nodeName", "e.target.type" and many more...

James
  • 4,644
  • 5
  • 37
  • 48
Tarik
  • 4,270
  • 38
  • 35
  • 6
    Actually it should be `e.target.nodeName === 'INPUT' && e.target.type !== 'textarea'`. With the specified code it will allow to submit forms if a radio or checkbox are focused. – afnpires May 18 '16 at 13:50
  • How would you limit this to an input by ID? i.e. only work on `` – NuclearApe Sep 05 '19 at 12:55
  • Figured it out, add `&&e.target.id=='noenter'` after `e.target.type=='text'` – NuclearApe Sep 05 '19 at 13:00
  • You probably want to be able to only press enter on textareas and buttons, so really the code should be: `e.target.type != 'textarea' && e.target.type != 'submit' && e.target.type != 'button'`. – Pluto Nov 19 '21 at 22:54
52

In your form tag just paste this:

onkeypress="return event.keyCode != 13;"

Example

<input type="text" class="search" placeholder="search" onkeypress="return event.keyCode != 13;">

This can be useful if you want to do search when typing and ignoring ENTER.

/// Grab the search term
const searchInput = document.querySelector('.search')
/// Update search term when typing
searchInput.addEventListener('keyup', displayMatches)
Norfeldt
  • 8,272
  • 23
  • 96
  • 152
YASH GAUTAMI
  • 673
  • 1
  • 6
  • 11
28

try this ^^

$(document).ready(function() {
        $("form").bind("keypress", function(e) {
            if (e.keyCode == 13) {
                return false;
            }
        });
    });

Hope this helps

Kent
  • 2,952
  • 2
  • 25
  • 42
  • 3
    This is a better solution than the selected because it will only selected the selected form. I would recommend, adding an ID or class to the form and selecting it that way. I could see another developer coming along, developing their own form and being frustrated that their form doesn't work when you hit enter. `$("#id-of-form")` or even better `$("form.form--disable-enter-key")` – StingeyB Jul 16 '15 at 20:19
10

For a non-javascript solution, try putting a <button disabled>Submit</button> into your form, positioned before any other submit buttons/inputs. I suggest immediately after the <form> opening tag (and using CSS to hide it, accesskey='-1' to get it out of the tab sequence, etc)

AFAICT, user agents look for the first submit button when ENTER is hit in an input, and if that button is disabled will then stop looking for another.

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.

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.)

https://www.w3.org/TR/html5/forms.html#implicit-submission

However, I do know that Safari 10 MacOS misbehaves here, submitting the form even if the default button is disabled.

So, if you can assume javascript, insert <button onclick="return false;">Submit</button> instead. On ENTER, the onclick handler will get called, and since it returns false the submission process stops. Browsers I've tested this with won't even do the browser-validation thing (focussing the first invalid form control, displaying an error message, etc).

Community
  • 1
  • 1
Erics
  • 803
  • 9
  • 23
  • 1
    THKS, this sould be the selected answer! No need for elaborate code, no dependancy on frameworks like jQuery and no need to change the rest of the form (or at least submit) tnto a work around. `` as the first control did the trick for me. ... and I didn't have to change anything in the rest of my form. Sometimes it actually helps to RTFM (in this case the specs :-) – Michael Apr 05 '19 at 09:48
  • This seems to disable the button all-together, though, which isn't what the author is looking for it seems? If they're in my boat, they were just trying to unmap it from enter. – mochsner Nov 12 '21 at 23:32
  • @mochsner You can have more than one submit button. The first gets targeted by ENTER (even if it is hidden), any other can be clicked. So, technically not unmapping ENTER, but instead mapping to a dead submit button. Same thing. – Erics Nov 13 '21 at 15:40
8

The solution is so simple:

Replace type "Submit" with button

<input type="button" value="Submit" onclick="this.form.submit()" />
Dmitry
  • 6,716
  • 14
  • 37
  • 39
Samir Patel
  • 167
  • 1
  • 7
  • This solution breaks the form completely for people with JavaScript disabled, though. By using JavaScript to override the Enter key, the default behaviour is left working for non-Javascript browsers and people using accessibility tools. – John Y Jan 14 '21 at 12:37
8

this is in pure javascript

        document.addEventListener('keypress', function (e) {
            if (e.keyCode === 13 || e.which === 13) {
                e.preventDefault();
                return false;
            }
            
        });
Lakshan
  • 81
  • 1
  • 2
6

Here's a simple way to accomplish this with jQuery that limits it to the appropriate input elements:

//prevent submission of forms when pressing Enter key in a text input
$(document).on('keypress', ':input:not(textarea):not([type=submit])', function (e) {
    if (e.which == 13) e.preventDefault();
});

Thanks to this answer: https://stackoverflow.com/a/1977126/560114.

Community
  • 1
  • 1
Matt Browne
  • 12,169
  • 4
  • 59
  • 75
3

Just add following code in <Head> Tag in your HTML Code. It will Form submission on Enter Key For all fields on form.

<script type="text/javascript">
    function stopEnterKey(evt) {
        var evt = (evt) ? evt : ((event) ? event : null);
        var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
        if ((evt.keyCode == 13) && (node.type == "text")) { return false; }
    }
    document.onkeypress = stopEnterKey;
</script>
Kailas Mane
  • 1,877
  • 1
  • 15
  • 12
2

You can try something like this, if you use jQuery.

$("form").bind("keydown", function(e) {
   if (e.keyCode === 13) return false;
 });

That will wait for a keydown, if it is Enter, it will do nothing.

Sastrija
  • 3,284
  • 6
  • 47
  • 64
Jaime Rodriguez
  • 343
  • 1
  • 8
1

I checked all the above solutions, they don't work. The only possible solution is to catch 'onkeydown' event for each input of the form. You need to attach disableAllInputs to onload of the page or via jquery ready()

/*
 * Prevents default behavior of pushing enter button. This method doesn't work,
 * if bind it to the 'onkeydown' of the document|form, or to the 'onkeypress' of
 * the input. So method should be attached directly to the input 'onkeydown'
 */
function preventEnterKey(e) {
    // W3C (Chrome|FF) || IE
    e = e || window.event;
    var keycode = e.which || e.keyCode;
    if (keycode == 13) { // Key code of enter button
        // Cancel default action
        if (e.preventDefault) { // W3C
            e.preventDefault();
        } else { // IE
            e.returnValue = false;
        }
        // Cancel visible action
        if (e.stopPropagation) { // W3C
            e.stopPropagation();
        } else { // IE
            e.cancelBubble = true;
        }
        // We don't need anything else
        return false;
    }
}
/* Disable enter key for all inputs of the document */
function disableAllInputs() {
    try {
        var els = document.getElementsByTagName('input');
        if (els) {
            for ( var i = 0; i < els.length; i++) {
                els[i].onkeydown = preventEnterKey;
            }
        }
    } catch (e) {
    }
}
Dimon579
  • 11
  • 2
1

I think setting a class to a form is much better. so I coded that:

HTML

<form class="submit-disabled">

JS

/**
 * <Start>
 * Submit Disabled Form
 */
document
    .querySelector('.submit-disabled')
    .addEventListener('submit', function (e) {

        e.preventDefault()
    });
/**
 * </End>
 * Submit Disabled Form
 */

And also if you want to disable submitting only when Enter Key press:

/**
 * <Start>
 * Submit Disabled Form
 */
document
    .querySelector('.submit-disabled')
    .addEventListener('keypress', function (e) {
        if (e.keyCode === 13) {
            e.preventDefault()
        }
    });
/**
 * </End>
 * Submit Disabled Form
 */
Arash Younesi
  • 1,671
  • 1
  • 14
  • 23
  • This will not work if the form elements are created (dynamically) after that JavaScript runs, correct? I have a single-page app wherein there are lots of forms for UI/layout, but I don't ever want the "enter" key to trigger submission. It used to be easy to solve by setting a submit handler on the body element (event would bubble), but this doesn't appear to work any more, so now I am having to set `onSubmit="return false"` on every form (or doing something similar like you have). If anyone knows of a better / more scalable solution please share. – jacobq Jan 19 '22 at 23:03
0

in HTML file:

@keypress="disableEnterKey($event)"

in js file:

disableEnterKey(e) {
  if (e.keyCode === 13) {
    e.preventDefault();
  }
}
0

First you need to disable the form on submit, but re-enable it when clicked on the button. which or keycode is not used in this case, avoiding some problems with compatibility.

    let formExample = document.getElementbyId("formExample");//selects the form
    formExample.addEventListener("submit", function(event){ //must be used "submit"
       event.preventDefault();// prevents "form" from being sent
    })

To reactivate and submit the form by clicking the button:

    let exampleButton = document.getElementById("exampleButton");
    exampleButton.addEventListener("click", activateButton); //calls the function "activateButton()" on click 
    function activateButton(){
       formExample.submit(); //submits the form
    }

a variation of this would be

    let exampleButton = document.getElementById("exampleButton");
    exampleButton.addEventListener("click", activateBtnConditions); //calls the function "activateBtnConditions()" on click
    function activateBtnConditions(){
       if(condition){
          instruction
       }
       else{
          formExample.submit()
       }
    }
Dharman
  • 30,962
  • 25
  • 85
  • 135
luk267
  • 1
0

Here is a modern, simple and reactive solution which works in:

  1. React, Solidjs, JSX etc.
  2. is written in Typescript
  3. supports server-side rendering (SSR)
  4. all modern browsers
  5. does NOT require jQuery
  6. blocks ALL Enter keys outside of <textarea> where you want to allow Enter
// avoids accidential form submission, add via event listener
function blockEnterKey(e: KeyboardEvent) {
  if (e.key == "Enter" && !(e.target instanceof HTMLTextAreaElement)) {
    e.preventDefault()
  }
}

// add the event listener before the rendering return in React, etc.
if (typeof window !== undefined) {
  window.addEventListener("keydown", blockEnterKey)
  // the following line is for Solidjs. React has similar cleanup functionality
  // onCleanup(() => document.body.removeEventListener("keydown", blockEnterKey))
}

return(
  <form>
  ...
  </form>
)
Sebastian
  • 8,952
  • 3
  • 32
  • 30
-2

The better way I found here:

Dream.In.Code

action="javascript: void(0)" or action="return false;" (doesn't work on me)

CKE
  • 1,533
  • 19
  • 18
  • 29
  • 2
    while the page at the link can contain the solution, it's always better to put the relevant informations in the answer and give the link only as reference... – DaFois Jul 22 '18 at 12:57