Disable form submit on enter keypress    March 13, 2005    75

I needed a JavaScript function that disables form submission when enter key is pressed. I’ve looked around and all solutions worked only in IE and I needed it to work in FireFox as well.

Finally after some more reading I found a solution how it can be done. Here is the function that I created:

<script language="JavaScript">
function disableEnterKey(e)
     var key;

          key = window.event.keyCode;     //IE
          key = e.which;     //firefox

     if(key == 13)
          return false;
          return true;

All you need to do is to add onKeyPress event to, for example, text element and call this function. Something like this:

<input type="text" name="mytext" onKeyPress="return disableEnterKey(event)">


Anurag January 21st, 2008 at 8:53 am

page does not refresh when submitting the form in ruby on rails here is the code for view and controller
view –

logins_path do |f| -%>



Confirm Password

‘login’, :label => “(human authentication)”) %>

controller –

class LoginsController [:index]

# render new.rhtml

def new

def create
cookies.delete :auth_token
# protects against session fixation attacks, wreaks havoc with
# request forgery protection.
# uncomment at your own risk
# reset_session
@login = Login.new(params[:login])
@login.captcha= params[:login][:captcha]
@login.captcha_key = params[:login][:captcha_key]
session[:login_id]= @login.id
if @login.save_with_captcha
self.current_login = @login
#flash[:notice] = “Thanks for signing up!”
render :text => ‘Thanks for Registrations! check your email for confirmation’
#rescue ActiveRecord::RecordInvalid
render :action => ‘new’

def confirmation_hash(string)
Digest::SHA1.hexdigest(string + “secret word”)

def confirmation_email
@login = Login.find(params[:login_id])
# if the passed hash matches up with a User, confirm him, log him in, set proper flash[:notice], and stop looking
if @login.confirm_hash== (params[:hash]).to_s
# @login.update_attributes(:email_confirmed => true)
flash[:notice] = “Email #{@login.email} is confirmed Welcome #{@login.email}”

flash[:notice] = “Not confirmed.”
def password_requested

def new_password
length = 6
chars = (‘a’..’z’).to_a + (‘A’..’Z’).to_a + (‘1′..’9′).to_a – [‘o’, ‘O’, ‘i’, ‘I’]

Array.new(length) { chars[rand(chars.size)] }.join
@newpass = “”
1.upto(length) { |i| @newpass ‘login’, :action => ‘index’
flash[:notice] = (‘email address not found’)
# set password


def confirm_password
if @login.save
flash[:notice] = “password is confirmed”
flash[:notice] = “Not change.”

Jepoy November 26th, 2007 at 10:19 am

form id=”frmCreatePO” runat=”server” onkeypress=”return event.keyCode!=13″

Jepoy November 26th, 2007 at 10:18 am

just include this on your form tag…

like this

works fine on my application.

The Traveller November 24th, 2007 at 4:24 pm

Congratulations! I was search by a lot of websites, but this is the unic that explanation about the way to call this function: onKeyPress=”return disableEnterKey(event)”

The RETURN expression on the calling fix my problems with mozila.

Thank you!!!

Pritesh Patel October 28th, 2007 at 8:47 pm

Thanks for the script!

Cor Knops September 22nd, 2007 at 5:31 pm

Hello Slobodan,

I tried your script but it doesn’t work… i.e. the form is sent when I hit the enter-key. I have built it in in a ASP-file which contains both VB- as well as Java-script. Does this influence the functioning of your script ??

Jeff Sailers September 22nd, 2007 at 5:23 am

Thanks for taking the time to share your hard work. It was just what I needed. Well Done!

Kier September 7th, 2007 at 4:17 pm

nice work, first time I googled something I needed and got what I needed straight away.

Xavier Vallverdú. Tarragona. Spain September 5th, 2007 at 5:37 pm

text omited in the last comment:

in the label…

form id=”form1″ name=”form1″ method=”post” onKeyPress=”return disableEnterKey(event)” action=”ins_form2.asp”

Xavier Vallverdú. Tarragona. Spain September 5th, 2007 at 5:36 pm

Slobodan, good code.

I captured the event in the label

It works properly for all “Enter key” pressed into the form


Anonymous August 6th, 2007 at 4:27 pm

this was really handy. I could add the onKeyPress event in order to nullify the return key, and another onKeyUp to work my autocomplete file

Website Design Bolton Manchester July 28th, 2007 at 12:30 am

Excellent, i’ve been looking for a script like this for ages…!

greatcan July 18th, 2007 at 9:35 pm

Thanks, this script helped me a lot. Awesome! Just what I was looking for :D

Gurvinder Pal Singh July 16th, 2007 at 11:10 am

Hi , I need to implement ctrl+entr key for inserting a line in the textbox and entr key for submitting the form…if any one could help me

Gurvinder Pal Singh July 16th, 2007 at 11:06 am

Hi , I need to implement + key for inserting a line in the textbox and key for submitting the form…if any one could help me

GDmac July 13th, 2007 at 4:18 pm

call it with [input onkeypress=’noenter(event);’ value=’xx’]

GDmac July 13th, 2007 at 4:15 pm

This next one works on firefox, safari and IE

function noenter(evt) {
evt = (evt) ? evt : ((window.event) ? window.event : “”)
if (evt) {
// process event here
// alert( evt.keyCode); // IE and Safari
// alert( evt.which); // FF
return !( evt.keyCode==13 || evt.which==13 );

with a

with help from http://developer.apple.com/internet/webcontent/eventmodels.html

Miroslav Rudisin July 9th, 2007 at 1:14 pm

less uglier hack, which disables submitting of form

var theForm = document.getElementById(‘theForm’);
var submitButton = document.getElementById(‘submitButton’);

var canSubmit=false;
theForm.onsubmit = function(){ return canSubmit; }
submitButton.onfocus = submitButton.onmouseover = function(){ canSubmit=true; }
submitButton.onblur = submitButton.onmouseout = function(){ canSubmit=false; }

Kevin Williams June 6th, 2007 at 12:12 pm

This worked perfectly for what I needed it for.

I am using mootools Fx.Slide, when you press the Enter key it toggles the divs in and out, which messes up the whole function.

So I used the javascript function, but called it by doing the following:

This way is disables all Enter key presses on the page, not just specific elements. This forces the user to click the “Submit” button, which is perfect for what I needed.

Carol May 28th, 2007 at 7:14 am

THANKYOU zzzzzzzzzz and Slobodan! Everyone else only offered IE solutions! It works on my form and I’m only a beginner.

David May 10th, 2007 at 10:03 am

i am using ajax for autocomplete textbox but wen a i hit enter it submits the form…if any one could help me

Ciprian M. April 28th, 2007 at 2:51 pm

Here’s one more:
I have a form which includes a textarea box. The enter key is used to submit the form (works fine actually). Here’s the javascript:

function ifEnter(field,event) {
var theCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if (theCode == 13){
return false;
return true;

How do I let Shift-Enter or better Alt-Enter to jump to next line of the box? (multiline behaviour)

aflatten April 26th, 2007 at 8:48 pm

Hi all —

The code above that disabled enter key submitting doesn’t work for Firefox Here’s some code that fixes this:

{ return ((event.keyCode ? event.keyCode : event.which ? event.which : event.charCode) != 13; }

Moiz Siddiqui April 12th, 2007 at 9:39 pm

gr8 work guys.. finally i was able to disable refresh , backspace and ctrl + n
keep up the gudd work

Anonymous February 27th, 2007 at 11:28 pm

I can find many things that I look for here! Thank you very much!

for a student February 22nd, 2007 at 11:27 am

This site is truly a great resource thanks for all your hard work

GaryO February 2nd, 2007 at 12:59 am

So Jeff… You solution worked GREAT!!! However, the only problem I am having is that Firefox doesn’t honor the stopPropagation() request…ONLY on the Backspace!!! :( I am going to look around, but any ideas why ??? Driving me nuts as this is what I wanted to prevent in the first place.

Steve January 23rd, 2007 at 1:17 am

To disable the “back” button, it’s probably better to spawn a spearate window at some point
in your process. I use this routine to do so.

function Popper(parms, url) {
var parms = parms.toLowerCase();
var parmarray = parms.split(“,”);
var winname=”Popper”;
var siz = parmarray[0];
var siz = siz.toUpperCase();
var sc = 1;
// default values
var wd = “width=” + ((window.screen.availWidth/8)*6);
var ht = “height=” + ((window.screen.availHeight/8)*6);
var col = “left=” + ((window.screen.availWidth/8));
var row = “top=” + ((window.screen.availHeight/8));
var mbar=”menubar=0″;
var tbar=”toolbar=0″;
var loc=”location=0″;
var dir=”directories=0″;
var stat=”status=0″;
var sbar=”scrollbars=1″;
var resiz=”resizable=1″;
// end defaults
if(siz == “FULL”) {
wd = “width=” + (window.screen.availWidth – 20);
ht = “height=” + (window.screen.availHeight – 40);
col = “left=0″;
row = “top=0″;
if(siz == “LARGE”) {
wd = “width=” + ((window.screen.availWidth/8)*7);
ht = “height=” + ((window.screen.availHeight/8)*7 – 20);
col = “left=0″;
row = “top=0″;
if(siz == “TALL”) {
wd = “width=” + ((window.screen.availWidth/8)*4);
ht = “height=” + ((window.screen.availHeight/8)*6 – 20);
col = “left=” + ((window.screen.availWidth/5));
row = “top=” + ((window.screen.availHeight/14));
if(siz == “MEDIUM”) {
wd = “width=” + ((window.screen.availWidth/8)*6);
ht = “height=” + ((window.screen.availHeight/8)*6);
col = “left=” + ((window.screen.availWidth/8));
row = “top=” + ((window.screen.availHeight/8));
if(siz == “SMALL”) {
wd = “width=” + ((window.screen.availWidth/2));
ht = “height=” + ((window.screen.availHeight/2));
col = “left=” + ((window.screen.availWidth/4));
row = “top=” + ((window.screen.availHeight/4));
if(siz == “XSMALL”) {
wd = “width=” + ((window.screen.availWidth/4));
ht = “height=” + ((window.screen.availHeight/4));
col = “left=” + ((window.screen.availWidth/8)*3);
row = “top=” + ((window.screen.availHeight/8)*3);
// replace defaults with passed parms
for (x=1;x -1)
winname = parmarray[x];
winname = winname.replace(‘name=’,”);
if (parmarray[x].search(‘menubar’) > -1)
mbar = parmarray[x];
if (parmarray[x].search(‘toolbar’) > -1)
tbar = parmarray[x];
if (parmarray[x].search(‘location’) > -1)
loc = parmarray[x];
if (parmarray[x].search(‘directories’) > -1)
dir = parmarray[x];
if (parmarray[x].search(‘status’) > -1)
stat = parmarray[x];
if (parmarray[x].search(‘scrollbars’) > -1)
sbar = parmarray[x];
if (parmarray[x].search(‘resizable’) > -1)
resiz = parmarray[x];
if (parmarray[x].search(‘width’) > -1)
wd = parmarray[x];
if (parmarray[x].search(‘height’) > -1)
ht = parmarray[x];
if (parmarray[x].search(‘left’) > -1)
col = parmarray[x];
if (parmarray[x].search(‘top’) > -1)
row = parmarray[x];
settings = wd + “,” + ht + “, ” + row + “, ” + col + “, ” + mbar + “, ” + tbar + “, ” + loc + “, ” + dir + “, ” + stat + “, ” + sbar + “, ” + resiz;
PopUp = window.open(url, winname, settings);

Dhruv January 22nd, 2007 at 1:24 pm

None of the above code works for Firefox
Does anybody have idea how to get it work?

asd as January 11th, 2007 at 5:52 am

// Internet Explorer// Internet Explorer// Internet Explorer

Gilbert January 2nd, 2007 at 12:50 pm

Good code, Thank You
but problem to disable CTRL++ (107)
Who makes a zoom in IE7
Can any body help ?

Anonymous January 2nd, 2007 at 5:17 am

I really, truly am glad I found this site. It has answered so many questions for me. I will be back. Thank You

James November 29th, 2006 at 5:16 pm

Cheers for the code

Anirban kundu November 28th, 2006 at 7:43 pm

I want to disable (!ӣ$%^&*|()) keys i.e when SHIFT +
1/2/3/4/5/6/7/8/9 is pressed. have written a function that
disables non numeric code to be entered on key down.

Can any body help ?

Jared November 3rd, 2006 at 6:30 pm

I tried using onkeypress=”return event.keyCode!=13? and IE gave an object error on KeyCode so I wrote this and found it works better in firefox and IE

return (window.event)? (window.event.keyCode != 13) : (e.which != 13);

Geoff Barnham September 27th, 2006 at 5:11 pm

I am not a programmer so I do have a problem implementing the previous posts but I have a big problem!
E-gold do not have an encripted form, like Paypal, so anyone can “view source” and see where they will be re-directed after payment.
I believe “view source” is ctrl+u, keycode 85 but I don’t know how to add the code shown in Jeff Gordons post.
Can anyone help me with this specific problem please?

marmot September 22nd, 2006 at 6:13 am

to Basti – Thanks! Just what I needed

Sarah Gray September 7th, 2006 at 6:32 pm

Addendum to above: bug only occurs if backspace is the FIRST badKey I press outside of the textbox. If I don’t place cursor in textbox first and I hit enter or ctrl-n, or any of the other combinations BEFORE hitting backspace, then backspace behaves correctly. But if I come to the page, do nothing but hit backspace outside of a textbox as the first thing I do, it acts like a back-button.

Sarah Gray September 7th, 2006 at 6:28 pm

@ Jeff Gordon
This is great, thanks so much for posting this.

One small bug I noticed (and I have not tried to debug yet but if/when I do I will post here) is on FF ( on PC (XP Pro SP2).

When I place my cursor in a textarea box as the first thing I do on the page (even if I do nothing in the textarea), then when I place it s/where else on the page and hit backspace, the code works perfectly (you see ‘backspace disabled in status bar and nothing happens). However, if I do not put the cursor in the textarea first and simply hit backspace from s/where on the page, it does not honor the rule — it acts like the back-button. I do not see this in IE. I have not tested on a mac yet.

Anonymous August 25th, 2006 at 3:05 pm

To disable back, you simply need to include this js code:


GowriShankar August 25th, 2006 at 9:24 am

Could any one tell us how to disable the “Back button” from the
Ie / FF

Brad August 24th, 2006 at 10:59 pm

In Visual Studio .NET 2005 using ASP 2.0, I cant figure out why when I call the disable key function the window.open() command does not execute. As well when debugging it has an issue with the BadKeys.single call.

Brian Cothran August 22nd, 2006 at 10:04 pm

Side Note – the following code snippet disables keychecking on some older versions of Firefox (ie at least version 1.07):
function addKeyEvent() {
// Specific function for this particular browser
var e = ‘keydown’;

I didn’t spend the time to find out or to see if it blocked the “t” key on 1.07 either cuz I just upgraded to 1.5 to see if the corrected code worked (and it does for 1.5).

Hope it helps somebody.

Doo August 17th, 2006 at 12:16 pm

Thanks you ZZZZZ!!
That just was what I was looking for.

Simon August 7th, 2006 at 7:19 am

Awesome! I’ve been looking for this one.

Marcos August 4th, 2006 at 6:10 pm

Thanks for the code :-)

Mark Smith July 25th, 2006 at 4:50 pm

@Jeff Gordon
I’ve found a slight bug which will stop your code working in Firefox (and possibly others)

function addKeyEvent() {
// Specific function for this particular browser
var e = (document.addEventListener) ? ‘keypress’ : ‘keydown’;

The keypress event is incorrect it should always be keydown.
The reason for this is because the letter t using the keypress event has the keyCode 116 which is the
same as F5 (Refresh) and the letter z has the keyCode 122 which is the same as F11 (Full Screen).

Replace the above section with:
function addKeyEvent() {
// Specific function for this particular browser
var e = ‘keydown';

Hope this has helped some-one :)

Basti July 17th, 2006 at 9:42 am

@Rhaine – as far as I know you cannot use Vinnie’s code to disable CTRL because it’s usually pressed along with another key. If you’d like to disable CTRL you should take a look at this: Disable ctrl + n and other ctrl + key combinations in JavaScript

Rhaine July 15th, 2006 at 6:41 pm

i don’t get it vinnie… what if you wanna disable just ctrl? how would you do it it with your script? what do i need to substitute? the keycode? and the which? it gives me an error that i need to define (e)
help.. thanks

Anonymous July 7th, 2006 at 3:45 am


vinnie June 19th, 2006 at 10:57 pm

oops, add a question mark after (window.event), that should be a condensed if statement

vinnie June 19th, 2006 at 10:55 pm

A 2-line version ;)

function disableEnterKey(e)
var key = (window.event) event.keyCode : e.which;
return (key != 13);

Vijay June 15th, 2006 at 12:24 pm

Can anyone help me with the same issue (disable “ctrl + n” keys
) in Mozilla firefox

Miranda May 11th, 2006 at 11:20 pm

wow thanks!! I have been looking for an cross browser way to prevent the F5 refresh and backspace

don April 21st, 2006 at 3:15 pm

Great!!! been looking for just this code. Thanks very much

chil December 8th, 2005 at 12:41 am

This is really great!
Now if somebody can tell me how to disable the browser back button too …

Jeff Gordon November 3rd, 2005 at 4:26 pm

This has worked great for me.
– Jeff Gordon

// ============= DisableKeys.js =============//

// Keys to be disabled can be added to the lists below.
// The number is the key code for the particular key
// and the text is the description displayed in the
// status window if the key [combination] is pressed.

var badKeys = new Object();
badKeys.single = new Object();
badKeys.single[‘8′] = ‘Backspace outside text fields';
badKeys.single[’13’] = ‘Enter outside text fields';
badKeys.single[‘116′] = ‘F5 (Refresh)';
badKeys.single[‘122′] = ‘F11 (Full Screen)';

badKeys.alt = new Object();
badKeys.alt[’37’] = ‘Alt+Left Cursor';
badKeys.alt[’39’] = ‘Alt+Right Cursor';

badKeys.ctrl = new Object();
badKeys.ctrl[’78’] = ‘Ctrl+N';
badKeys.ctrl[’79’] = ‘Ctrl+O';

function checkKeyCode(type, code) {
if (badKeys[type]) {
return true;
} else {
return false;
function getKeyText(type, code) {
return badKeys[type];

var ie=document.all;
var w3c=document.getElementById&&!document.all;

function keyEventHandler(evt) {
this.target = evt.target || evt.srcElement;
this.keyCode = evt.keyCode || evt.which;
var targtype = this.target.type;
if (w3c) {
if (document.layers) {
this.altKey = ((evt.modifiers & Event.ALT_MASK) > 0);
this.ctrlKey = ((evt.modifiers & Event.CONTROL_MASK) > 0);
this.shiftKey = ((evt.modifiers & Event.SHIFT_MASK) > 0);
} else {
this.altKey = evt.altKey;
this.ctrlKey = evt.ctrlKey;
// Internet Explorer
} else {
this.altKey = evt.altKey;
this.ctrlKey = evt.ctrlKey;
// Find out if we need to disable this key combination
var badKeyType = “single”;
if (this.ctrlKey) {
badKeyType = “ctrl”;
} else if (this.altKey) {
badKeyType = “alt”;
if (checkKeyCode(badKeyType, this.keyCode)) {
return cancelKey(evt, this.keyCode, this.target, getKeyText(badKeyType, this.keyCode));

function cancelKey(evt, keyCode, target, keyText) {
if (keyCode==8 || keyCode==13) {
// Don’t want to disable Backspace or Enter in text fields
if (target.type == “text” || target.type == “textarea”) {
window.status = “”;
return true;
if (evt.preventDefault) {
} else {
evt.keyCode = 0;
evt.returnValue = false;
window.status = keyText+” is disabled”;
return false;
// ============= DisableKeys.js =============//

// ============= PageSetup.inc =============//


function addEvent(obj, evType, fn, useCapture) {
// General function for adding an event listener
if (obj.addEventListener) {
obj.addEventListener(evType, fn, useCapture);
return true;
} else if (obj.attachEvent) {
var r = obj.attachEvent(“on” + evType, fn);
return r;
} else {
alert(evType+” handler could not be attached”);
function addKeyEvent() {
// Specific function for this particular browser
var e = (document.addEventListener) ? ‘keypress’ : ‘keydown';
//To disable the right mouse button
document.oncontextmenu=new Function(“return false”);

” rel=”stylesheet” type=”text/css”>

// ============= PageSetup.inc =============//

Ajai Joy October 24th, 2005 at 8:15 am

Thanks. it works on firefox 10.0.3

Basti June 22nd, 2005 at 4:09 pm

David, you can always put onKeyPress into form tag, instead of putting it to a particular element.

Problem with this is that although it works in FireFox 1.0.4 and Internet Explorer 6 it might not work in other browsers. For example, I tested this in FireFox 1.0 and it doesn’t work (i.e. form gets submitted).

You can always make a kind of iterator which will set onKeyPress attribute to each form element, but it would require a bit more coding.

David June 20th, 2005 at 9:42 pm

But the OnKeyPress event Does not work if the text box (or any other element) is disabled.

Is there any other way to get around this issue? i.e. disable the Enter Key on a form level not just in an elment level

Thanks very much

yog June 4th, 2005 at 5:13 pm

Very usefull i have just implemented it and it works.

Basti April 25th, 2005 at 4:43 pm

Yes, you can do that in newer FireFox (e.g. 1.0.3), but in FireFox 1.0.0 solution you proposed doesn’t work. I guess that it was some small bug that they fixed.

Nevertheless, when I made that script current FireFox version <1.0.3 – and I had to make it work.

zzzzzzzzzz April 25th, 2005 at 4:25 pm

or you can use one line:

onkeypress=”return event.keyCode!=13″

i’ve tested in firefox and IE