Web Design
Web Design Surrey Web Design Services in Surrey

Tutorial Categories

Links & Services

Mailing List

For special offers and annoucements, please enter your email address below.

JavaScript Disable Enter Key on Form Submission

In this tutorial, I'm going to show you how to disable the "Enter" Key. A problem that can often occur is when users submit a form twice. This script prevents the enter key from being allowed to submit the form. Thus, helping to keep your intended web form data flow intact - reducing the risk of duplicate submissions. The result will look like this:

Disabled Enter Key Example(Try typing some text and pressing the "Enter" key):

How to do it:

You will need to add the script and the text field as follows - please follow the comments in the code.

<?php /* Disable the enter key */ ?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Confirmation Dialogue Boxes</title> 

<script type="text/javascript"> 

//create a function that accepts an input variable (which key was key pressed) 
function disableEnterKey(e){ 

//create a variable to hold the number of the key that was pressed      
var key; 

    //if the users browser is internet explorer 
    //store the key code (Key number) of the pressed key 
    key = window.event.keyCode; 
    //otherwise, it is firefox 
    } else { 
    //store the key code (Key number) of the pressed key 
    key = e.which;      
    //if key 13 is pressed (the enter key) 
    if(key == 13){ 
    //do nothing 
    return false; 
    } else { 
    //continue as normal (allow the key press for keys other than "enter") 
    return true; 
//and don't forget to close the function     



<!-- Here we have a form field with it's "onKeyPress" event set to call our JavaScript function --> 
<input type="text" name="mytext" onKeyPress="return disableEnterKey(event)"> 

<? /* Tutorial by Marc Firth */ ?>


If the user is using a browser other than IE or Firefox the above code may not work - but as far as I know, it works in every browser I have tried it in (IE, Firefox, Chrome, Opera, Safari). You may also need to put this function on every form field.

The Output (Try typing some text and pressing the "Enter" key):

And just to prove it here's a normal textbox without the script. Try typing some text and pressing the "Enter" key. If the data is submitted it will appear in your address bar as a GET variable.

Normal Enter Key Example:

More JavaScript Tutorials

JavaScript Confirmation Dialogues

View More...