Prevent form submission on Enter key press

1,231,768

Solution 1

if(characterCode == 13)
{
    return false; // returning false will prevent the event from bubbling up.
}
else
{
    return true;
}

Ok, so imagine you have the following textbox in a form:

<input id="scriptBox" type="text" onkeypress="return runScript(event)" />

In order to run some "user defined" script from this text box when the enter key is pressed, and not have it submit the form, here is some sample code. Please note that this function doesn't do any error checking and most likely will only work in IE. To do this right you need a more robust solution, but you will get the general idea.

function runScript(e) {
    //See notes about 'which' and 'key'
    if (e.keyCode == 13) {
        var tb = document.getElementById("scriptBox");
        eval(tb.value);
        return false;
    }
}

returning the value of the function will alert the event handler not to bubble the event any further, and will prevent the keypress event from being handled further.

NOTE:

It's been pointed out that keyCode is now deprecated. The next best alternative which has also been deprecated.

Unfortunately the favored standard key, which is widely supported by modern browsers, has some dodgy behavior in IE and Edge. Anything older than IE11 would still need a polyfill.

Furthermore, while the deprecated warning is quite ominous about keyCode and which, removing those would represent a massive breaking change to untold numbers of legacy websites. For that reason, it is unlikely they are going anywhere anytime soon.

Solution 2

Use both event.which and event.keyCode:

function (event) {
    if (event.which == 13 || event.keyCode == 13) {
        //code to execute here
        return false;
    }
    return true;
};

Solution 3

event.key === "Enter"

More recent and much cleaner: use event.key. No more arbitrary number codes!

NOTE: The old properties (.keyCode and .which) are Deprecated.

const node = document.getElementsByClassName("mySelect")[0];
node.addEventListener("keydown", function(event) {
    if (event.key === "Enter") {
        event.preventDefault();
        // Do more work
    }
});

Modern style, with lambda and destructuring

node.addEventListener("keydown", ({key}) => {
    if (key === "Enter") // Handle press
})

Mozilla Docs

Supported Browsers

Solution 4

If you're using jQuery:

$('input[type=text]').on('keydown', function(e) {
    if (e.which == 13) {
        e.preventDefault();
    }
});

Solution 5

Detect Enter key pressed on whole document:

$(document).keypress(function (e) {
    if (e.which == 13) {
        alert('enter key is pressed');
    }
});

http://jsfiddle.net/umerqureshi/dcjsa08n/3/

Share:
1,231,768
Dushan Perera
Author by

Dushan Perera

❤️ building super 🚅 fast 🏎️ web experience 🚀 Azure functions &lt;⚡&gt; is my recent area of interest. Former ASP.NET MVP Please feel free to suggest improvements to my posts

Updated on January 01, 2022

Comments

  • Dushan Perera
    Dushan Perera over 2 years

    I have a form with two text boxes, one select drop down and one radio button. When the enter key is pressed, I want to call my JavaScript function, but when I press it, the form is submitted.

    How do I prevent the form from being submitted when the enter key is pressed?

  • Dushan Perera
    Dushan Perera almost 15 years
    I cant override onsubmit as i have another form submit in this page
  • the_drow
    the_drow almost 15 years
    yes you can. Javascript is prototype based language. document.forms["form_name"].onsubmit = fucntion() {}
  • Dushan Perera
    Dushan Perera almost 15 years
    I have another delete procedure to run when the form is submitted.So i want to maintain as it is
  • Admin
    Admin over 12 years
    Is this a situation where PreventDefualt can be used?
  • Les
    Les about 12 years
    Yes, instead of the return false.
  • Wk_of_Angmar
    Wk_of_Angmar about 11 years
    Instead of eval, you could build an array of the valid functions, then use .indexOf() to check whether the user's input is in that array, and call the function if it is. Reduces scope for errors/users screwing up.
  • Alex Spurling
    Alex Spurling about 11 years
    Why both event.which and event.keyCode?
  • user568109
    user568109 almost 11 years
    Some browsers support which others support keyCode. It is good practice to include both.
  • Manish Singh
    Manish Singh over 10 years
    Also use the keydown event instead of keyup or keypress
  • Pierre-Olivier Vares
    Pierre-Olivier Vares over 9 years
    keyup is fired AFTER the submission, and can't therefore cancel it.
  • Don Cheadle
    Don Cheadle over 8 years
    @Agiagnoc but what event should this be attached to ?
  • john-jones
    john-jones over 8 years
    @manish, keypress gives you more information to play with than keydown/up. stackoverflow.com/a/9905293/322537
  • Anders Kitson
    Anders Kitson almost 8 years
    IE does not support just event.keyCode, tested on a new windows tablet and return key wasn't firing my functions. Adding which as stated above should fix any IE bugs.
  • Donatas Navidonskis
    Donatas Navidonskis over 6 years
    set var charCode = parseInt((e.which) ? e.which : e.keyCode); and then compare if(charCode == 13) { // execute } return false;
  • John Slegers
    John Slegers over 6 years
  • eddyparkinson
    eddyparkinson about 6 years
    Why has client_id etc been included here? Is the code legit?
  • Nico Haase
    Nico Haase about 6 years
    This question is more than eight years old. Typescript did not exist then. So are you sure you're not answering an other question?
  • clockw0rk
    clockw0rk over 5 years
    isn't this just a macro or alias? is there any benefit in terms of performance by using this code?
  • Gibolt
    Gibolt over 5 years
    keyCode is deprecated. This is more readable and maintainable than a magic integer in your code
  • Jing He
    Jing He almost 4 years
    @Shyju if you want to run both: the action defined in the form tag and also the javascript triggered when pressing the submit button, you can just remove the code return false;, then both action will be triggered.
  • Danziger
    Danziger over 3 years
    While I agree with your note about keyCode and which being deprecated, I think developers should help make that transition by not supporting such legacy browsers, especially now that IE is officially dead and Edge has adopted Chromium. Anyway, a nice tool to inspect the different identifiers keys have is keyjs.dev
  • Danziger
    Danziger over 3 years
    For those wondering how to find the key value for different keys, you can use keyjs.dev
  • Alexander Nied
    Alexander Nied about 3 years
    In 2021, I believe this is the correct answer.
  • Tamil Vendhan Kanagarasu
    Tamil Vendhan Kanagarasu over 2 years
    Readable, yes! Cleaner? 13 is more clean than Enter. There was no questions like, is it "Enter" or "enter". If you can remember "Enter", you can always remember 13. It takes less room.
  • Greggory Wiley
    Greggory Wiley about 2 years
    Only works if you install jquery.
  • Dozie
    Dozie about 2 years
    @Josh, @JohnSlegers, @Danziger KeyboardEvent.code is now supported in major browser versions. So this response can be refactored to use: if (e.code === "Enter")
  • NetXpert
    NetXpert almost 2 years
    "abitrary"?! It has existed as a standard since the development of ASCII, ~1961! Itself having been based-upon / derived-from work that began with teletype machines starting 40 years before that! Though it may have begun as such, here, now, in 2022, 60+ years on from the development of that standard, and the ubiquitous implementations that stem therefrom, knowing that 0x0d / (dec)13 represents a carriage-return is well-beyond being just some 'arbitrary' value, and anyone who's been coding for longer than a year should know it as naturally/intrinsically as they know how to breathe air...🙄
  • Gibolt
    Gibolt almost 2 years
    Yes, the history is real. However the numbers are arbitrary, just like the arrangement of keys on a keyboard. Few devs have the list of char/key mappings memorized