380

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?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Shyju
  • 214,206
  • 104
  • 411
  • 497

20 Answers20

470
if(characterCode == 13) {
    // returning false will prevent the event from bubbling up.
    return false; 
} 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.

John Slegers
  • 45,213
  • 22
  • 199
  • 169
Josh
  • 44,706
  • 7
  • 102
  • 124
  • 1
    Is this a situation where PreventDefualt can be used? –  Sep 01 '11 at 18:05
  • Yes, instead of the return false. – Fabio Milheiro Mar 06 '12 at 12:21
  • 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. – Wk_of_Angmar Apr 09 '13 at 00:45
  • 7
    **[`keyCode` is now deprecated](https://developer.mozilla.org/en-US/docs/Web/Events/keypress)** – John Slegers Aug 24 '17 at 10:44
  • 3
    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 https://keyjs.dev – Danziger Sep 27 '20 at 04:53
  • @Josh, @JohnSlegers, @Danziger [KeyboardEvent.code](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code) is now supported in major browser versions. So this response can be refactored to use: `if (e.code === "Enter")` – Dozie Apr 21 '22 at 11:28
142

Use both event.which and event.keyCode:

function (event) {
    if (event.which == 13 || event.keyCode == 13) {
        //code to execute here
        return false;
    }
    return true;
};
Bradley4
  • 510
  • 1
  • 6
  • 13
Agiagnoc
  • 1,623
  • 1
  • 11
  • 8
126

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

Gibolt
  • 42,564
  • 15
  • 187
  • 127
  • isn't this just a macro or alias? is there any benefit in terms of performance by using this code? – clockw0rk Sep 28 '18 at 14:18
  • 1
    `keyCode` is deprecated. This is more readable and maintainable than a magic integer in your code – Gibolt Sep 28 '18 at 16:41
  • 2
    For those wondering how to find the `key` value for different keys, you can use https://keyjs.dev – Danziger Sep 27 '20 at 04:55
  • 2
    In 2021, I believe this is the correct answer. – Alexander Nied Feb 19 '21 at 17:22
  • 1
    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. – Tamil Vendhan Kanagarasu Nov 10 '21 at 08:51
  • "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... – NetXpert Jun 30 '22 at 17:57
  • 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 – Gibolt Jun 30 '22 at 18:04
82

If you're using jQuery:

$('input[type=text]').on('keydown', function(e) {
    if (e.which == 13) {
        e.preventDefault();
    }
});
Matt K
  • 6,620
  • 3
  • 38
  • 60
cowboy
  • 873
  • 7
  • 6
28

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/

Umer Qureshi
  • 1,736
  • 2
  • 20
  • 22
18

Override the onsubmit action of the form to be a call to your function and add return false after it, ie:

<form onsubmit="javascript:myfunc();return false;" >
Shyju
  • 214,206
  • 104
  • 411
  • 497
rpkelly
  • 2,076
  • 1
  • 20
  • 19
  • I cant override onsubmit as i have another form submit in this page – Shyju May 25 '09 at 03:44
  • 6
    yes you can. Javascript is prototype based language. document.forms["form_name"].onsubmit = fucntion() {} – the_drow May 25 '09 at 04:10
  • 1
    I have another delete procedure to run when the form is submitted.So i want to maintain as it is – Shyju May 25 '09 at 13:37
  • @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. – Jing He Jun 28 '20 at 05:33
17

A react js solution

 handleChange: function(e) {
    if (e.key == 'Enter') {
      console.log('test');
    }


 <div>
    <Input type="text"
       ref = "input"
       placeholder="hiya"
       onKeyPress={this.handleChange}
    />
 </div>
caffeinescript
  • 1,365
  • 2
  • 13
  • 27
10

So maybe the best solution to cover as many browsers as possible and be future proof would be

if (event.which === 13 || event.keyCode === 13 || event.key === "Enter")
Matt Doran
  • 2,050
  • 2
  • 16
  • 18
6

Here is how you can do it using JavaScript:

//in your **popup.js** file just use this function 

    var input = document.getElementById("textSearch");
    input.addEventListener("keyup", function(event) {
        event.preventDefault();
        if (event.keyCode === 13) {
            alert("yes it works,I'm happy ");
        }
    });
<!--Let's say this is your html file-->
 <!DOCTYPE html>
    <html>
      <body style="width: 500px">
        <input placeholder="Enter the text and press enter" type="text" id="textSearch"/> 
          <script type="text/javascript" src="public/js/popup.js"></script>
      </body>
    </html>
snnsnn
  • 10,486
  • 4
  • 39
  • 44
DINA TAKLIT
  • 7,074
  • 10
  • 69
  • 74
5

Below code will add listener for ENTER key on entire page.

This can be very useful in screens with single Action button eg Login, Register, Submit etc.

<head>
        <!--Import jQuery IMPORTANT -->
        <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>

         <!--Listen to Enter key event-->
        <script type="text/javascript">

            $(document).keypress(function (e) {
                if (e.which == 13 || event.keyCode == 13) {
                    alert('enter key is pressed');
                }
            });
        </script>
    </head>

Tested on all browsers.

Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
4

A little simple

Don't send the form on keypress "Enter":

<form id="form_cdb" onsubmit="return false">

Execute the function on keypress "Enter":

<input type="text" autocomplete="off" onkeypress="if(event.key === 'Enter') my_event()">
Community
  • 1
  • 1
rbz
  • 1,097
  • 13
  • 20
3

A jQuery solution.

I came here looking for a way to delay the form submission until after the blur event on the text input had been fired.

$(selector).keyup(function(e){
  /*
   * Delay the enter key form submit till after the hidden
   * input is updated.
   */

  // No need to do anything if it's not the enter key
  // Also only e.which is needed as this is the jQuery event object.
  if (e.which !== 13) {
       return;
  }

  // Prevent form submit
  e.preventDefault();

  // Trigger the blur event.
  this.blur();

  // Submit the form.
  $(e.target).closest('form').submit();
});

Would be nice to get a more general version that fired all the delayed events rather than just the form submit.

chim
  • 8,407
  • 3
  • 52
  • 60
3

A much simpler and effective way from my perspective should be :

function onPress_ENTER()
{
        var keyPressed = event.keyCode || event.which;

        //if ENTER is pressed
        if(keyPressed==13)
        {
            alert('enter pressed');
            keyPressed=null;
        }
        else
        {
            return false;
        }
}
Thanos
  • 341
  • 2
  • 4
2

Using TypeScript, and avoid multiples calls on the function

let el1= <HTMLInputElement>document.getElementById('searchUser');
el1.onkeypress = SearchListEnter;

function SearchListEnter(event: KeyboardEvent) {
    if (event.which !== 13) {
        return;
    }
    // more stuff
}
Wagner Pereira
  • 1,050
  • 11
  • 11
  • This question is more than eight years old. Typescript did not exist then. So are you sure you're not answering an other question? – Nico Haase Mar 14 '18 at 21:36
1

native js (fetch api)

document.onload = (() => {
    alert('ok');
    let keyListener = document.querySelector('#searchUser');
    // 
    keyListener.addEventListener('keypress', (e) => {
        if(e.keyCode === 13){
            let username = e.target.value;
            console.log(`username = ${username}`);
            fetch(`https://api.github.com/users/${username}`,{
                data: {
                    client_id: 'xxx',
                    client_secret: 'xxx'
                }
            })
            .then((user)=>{
                console.log(`user = ${user}`);
            });
            fetch(`https://api.github.com/users/${username}/repos`,{
                data: {
                    client_id: 'xxx',
                    client_secret: 'xxx'
                }
            })
            .then((repos)=>{
                console.log(`repos = ${repos}`);
                for (let i = 0; i < repos.length; i++) {
                     console.log(`repos ${i}  = ${repos[i]}`);
                }
            });
        }else{
            console.log(`e.keyCode = ${e.keyCode}`);
        }
    });
})();
<input _ngcontent-inf-0="" class="form-control" id="searchUser" placeholder="Github username..." type="text">
xgqfrms
  • 10,077
  • 1
  • 69
  • 68
1
<div class="nav-search" id="nav-search">
        <form class="form-search">
            <span class="input-icon">
                <input type="text" placeholder="Search ..." class="nav-search-input" id="search_value" autocomplete="off" />
                <i class="ace-icon fa fa-search nav-search-icon"></i>
            </span>
            <input type="button" id="search" value="Search" class="btn btn-xs" style="border-radius: 5px;">
        </form>

</div>

<script type="text/javascript">
    $("#search_value").on('keydown', function(e) {
        if (e.which == 13) {
             $("#search").trigger('click');
            return false;
        }
    });
    $("#search").on('click',function(){
        alert('You press enter');
    });
</script>
1
<form id="form1" runat="server" onkeypress="return event.keyCode != 13;">

Add this Code In Your HTML Page...it will disable ...Enter Button..

THE LIFE-TIME LEARNER
  • 1,476
  • 1
  • 8
  • 18
0

Cross Browser Solution

Some older browsers implemented keydown events in a non-standard way.

KeyBoardEvent.key is the way it is supposed to be implemented in modern browsers.

which and keyCode are deprecated nowadays, but it doesn't hurt to check for these events nonetheless so that the code works for users that still use older browsers like IE.

The isKeyPressed function checks if the pressed key was enter and event.preventDefault() hinders the form from submitting.

  if (isKeyPressed(event, 'Enter', 13)) {
    event.preventDefault();
    console.log('enter was pressed and is prevented');
  }

Minimal working example

JS

function isKeyPressed(event, expectedKey, expectedCode) {
  const code = event.which || event.keyCode;

  if (expectedKey === event.key || code === expectedCode) {
    return true;
  }
  return false;
}

document.getElementById('myInput').addEventListener('keydown', function(event) {
  if (isKeyPressed(event, 'Enter', 13)) {
    event.preventDefault();
    console.log('enter was pressed and is prevented');
  }
});

HTML

<form>
  <input id="myInput">
</form>

https://jsfiddle.net/tobiobeck/z13dh5r2/

Tobi Obeck
  • 1,918
  • 1
  • 19
  • 31
0

Use event.preventDefault() inside user defined function

<form onsubmit="userFunction(event)"> ...

function userFunction(ev) 
{
    if(!event.target.send.checked) 
    {
        console.log('form NOT submit on "Enter" key')

        ev.preventDefault();
    }
}
Open chrome console> network tab to see
<form onsubmit="userFunction(event)" action="/test.txt">
  <input placeholder="type and press Enter" /><br>
  <input type="checkbox" name="send" /> submit on enter
</form>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
-1

I used document on, which covers dynamically added html after page load:

  $(document).on('keydown', '.selector', function (event) {
    if (event.which == 13 || event.keyCode == 13) {
      //do your thang
    }
  });

Added updates from @Bradley4

sobelito
  • 1,525
  • 17
  • 13