For special offers and annoucements, please enter your email address below.
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:
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"> <head> <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 if(window.event){ //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; //otherwise } else { //continue as normal (allow the key press for keys other than "enter") return true; } //and don't forget to close the function } </script> </head> <body> <form> <!-- 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)"> </form> </body> </html> <? /* Tutorial by Marc Firth */ ?>
Notes:
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.
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.