Disable form submit on enter keypress March 13, 2005

Posted by Slobodan Kovacevic in : Programming , trackback

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;

     if(window.event)
          key = window.event.keyCode;     //IE
     else
          key = e.which;     //firefox

     if(key == 13)
          return false;
     else
          return true;
}
</script>

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)”>

Comments

1. zzzzzzzzzz - April 25, 2005

or you can use one line:

onkeypress=”return event.keyCode!=13″

i’ve tested in firefox and IE

2. Basti - April 25, 2005

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.

3. yog - June 4, 2005

Very usefull i have just implemented it and it works.

4. David - June 20, 2005

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

5. Basti - June 22, 2005

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.

6. Ajai Joy - October 24, 2005

Thanks. it works on firefox 10.0.3

7. Jeff Gordon - November 3, 2005

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][code]) {
return true;
} else {
return false;
}
}
function getKeyText(type, code) {
return badKeys[type][code];
}

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) {
evt.preventDefault();
evt.stopPropagation();
} 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’;
addEvent(document,e,keyEventHandler,false);
}
addKeyEvent();
//To disable the right mouse button
document.oncontextmenu=new Function(”return false”);

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

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

8. chil - December 8, 2005

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

9. don - April 21, 2006

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

10. Miranda - May 11, 2006

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

11. Vijay - June 15, 2006

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

12. My Tech Space :: How to disable enter key in form submission. :: June :: 2006 - June 16, 2006

[…] And then call this function in your HTML element (e.g input) onKeyPress=”return disableEnterKey(event)” Reference […]

13. AS Workshop » Disable ctrl + n and other ctrl + key combinations in JavaScript - June 17, 2006

[…] Few days ago Vijay asked if there’s a way to disable ctrl + n combination (open the new window shortcut. So I set out to create a small Java Script that disables any ctrl + key combination (e.g. ctrl + v, ctrl + c, ctrl + a, etc.). […]

14. vinnie - June 19, 2006

A 2-line version ;)

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

15. vinnie - June 19, 2006

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

16. Anonymous - July 7, 2006

cool

17. Rhaine - July 15, 2006

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

18. Basti - July 17, 2006

@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

19. Mark Smith - July 25, 2006

@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’;
addEvent(document,e,keyEventHandler,false);
}

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’;
addEvent(document,e,keyEventHandler,false);
}

Hope this has helped some-one :)

20. Marcos - August 4, 2006

Thanks for the code :-)

21. Simon - August 7, 2006

Awesome! I’ve been looking for this one.

22. Doo - August 17, 2006

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

23. Brian Cothran - August 22, 2006

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’;
addEvent(document,e,keyEventHandler,false);
}

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.

24. Brad - August 24, 2006

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.

25. GowriShankar - August 25, 2006

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

26. Anonymous - August 25, 2006

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

window.history.forward(1);

27. Sarah Gray - September 7, 2006

@ 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 (1.5.0.6) 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.

28. Sarah Gray - September 7, 2006

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.

29. marmot - September 22, 2006

to Basti - Thanks! Just what I needed

30. Geoff Barnham - September 27, 2006

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?

31. Jared - November 3, 2006

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);

32. Anirban kundu - November 28, 2006

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 ?

33. James - November 29, 2006

Cheers for the code

34. Anonymous - January 2, 2007

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

35. Gilbert - January 2, 2007

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

36. asd as - January 11, 2007

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

37. Dhruv - January 22, 2007

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

38. Steve - January 23, 2007

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);
PopUp.focus();
}

39. GaryO - February 2, 2007

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.

40. for a student - February 22, 2007

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

41. Anonymous - February 27, 2007

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

42. Moiz Siddiqui - April 12, 2007

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

43. aflatten - April 26, 2007

Hi all –

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

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

44. Ciprian M. - April 28, 2007

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){
document.forms[0].submit();
return false;
}
else
return true;
}

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

45. David - May 10, 2007

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

46. Carol - May 28, 2007

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

47. Kevin Williams - June 6, 2007

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.

48. lost node » Blog Archive » 80+ AJAX-Solutions For Professional Coding - July 3, 2007

[…] 38. Disable form submit on enter keypress […]

49. Miroslav Rudisin - July 9, 2007

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; }

50. GDmac - July 13, 2007

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

51. GDmac - July 13, 2007

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

52. Gurvinder Pal Singh - July 16, 2007

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

53. Gurvinder Pal Singh - July 16, 2007

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

54. greatcan - July 18, 2007

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

55. 80+ codigos AJAX profesionales « Quest’s Blog - July 24, 2007

[…] 38. Disable form submit on enter keypress […]

56. sastgroup.com » Blog Archive » 85 scripts ajax professionali - July 24, 2007

[…] 38. Disable form submit on enter keypress […]

57. Website Design Bolton Manchester - July 28, 2007

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

58. Anonymous - August 6, 2007

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

59. Xavier Vallverdú. Tarragona. Spain - September 5, 2007

Slobodan, good code.

I captured the event in the label

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

Thanks

60. Xavier Vallverdú. Tarragona. Spain - September 5, 2007

text omited in the last comment:

in the label…

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

61. Kier - September 7, 2007

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

62. EgyGuy » Blog Archive » 80+ AJAX-Solutions For Professional Coding - September 17, 2007

[…] 38. Disable form submit on enter keypress […]

63. Jeff Sailers - September 22, 2007

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

64. Cor Knops - September 22, 2007

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 ??

65. Obez Blog » 80+ AJAX-Solutions For Professional Coding - September 24, 2007

[…] 38. Disable form submit on enter keypress […]

66. Pritesh Patel - October 28, 2007

Thanks for the script!

67. 行搏客 » Smashing Magazine:80多个Ajax解决方案(1) - November 22, 2007

[…] 14、按回车键使form表单不能提交 […]

68. The Traveller - November 24, 2007

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!!!

69. Jepoy - November 26, 2007

just include this on your form tag…

like this

works fine on my application.

70. Jepoy - November 26, 2007

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

71. Worpress » Blog Archive » AJAX Developer’s Suite - December 27, 2007

[…] Disable form submit on enter keypress […]

72. best AJAX Solutions For Professional web design - The Arts Lab TurkeY - January 9, 2008

[…] 38. Disable form submit on enter keypress […]

73. NilDesign.ru » Blog Archive » 80 AJAX-Решений - January 13, 2008

[…] 38. Disable form submit on enter keypress […]

74. 80+ AJAX-Solutions For Professional Coding at egyptianwebdesigner.com - January 21, 2008

[…] 38. Disable form submit on enter keypress […]

75. Anurag - January 21, 2008

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| -%>

Email

Password

Confirm Password

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

controller -

class LoginsController [:index]

# render new.rhtml

def new
end

def create
cookies.delete :auth_token
# protects against session fixation attacks, wreaks havoc with
# request forgery protection.
# uncomment at your own risk
# reset_session
p”mmmmmm”
@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
Notifier.deliver_confirmation_email(@login,confirmation_hash(@login.email))
@login.confirm_hash=confirmation_hash(@login.email)
@login.save
#redirect_back_or_default(’/')
#flash[:notice] = “Thanks for signing up!”
render :text => ‘Thanks for Registrations! check your email for confirmation’
else
#rescue ActiveRecord::RecordInvalid
render :action => ‘new’
end
end

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

def confirmation_email
@login = Login.find(params[:login_id])
@login.save
# 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)
@login.email_confirmed=1
@login.save
flash[:notice] = “Email #{@login.email} is confirmed Welcome #{@login.email}”

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

end
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’
#end
else
flash[:notice] = (’email address not found’)
end
# set password

end

def confirm_password
@login=Login.find(params[:login_id])
@login.crypted_password=@login.encrypt(params[:newpass])
if @login.save
flash[:notice] = “password is confirmed”
else
flash[:notice] = “Not change.”
end
end
end