Disable form submit on enter keypress March 13, 2005
Posted by Slobodan Kovacevic in : Programming , trackbackI 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:
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:
Comments
or you can use one line:
onkeypress=”return event.keyCode!=13″
i’ve tested in firefox and IE
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.
Very usefull i have just implemented it and it works.
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
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.
Thanks. it works on firefox 10.0.3
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 =============//
This is really great!
Now if somebody can tell me how to disable the browser back button too …
Great!!! been looking for just this code. Thanks very much
wow thanks!! I have been looking for an cross browser way to prevent the F5 refresh and backspace
Can anyone help me with the same issue (disable “ctrl + n” keys
) in Mozilla firefox
[…] And then call this function in your HTML element (e.g input) onKeyPress=”return disableEnterKey(event)” Reference […]
[…] 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.). […]
A 2-line version
function disableEnterKey(e)
{
var key = (window.event) event.keyCode : e.which;
return (key != 13);
}
oops, add a question mark after (window.event), that should be a condensed if statement
cool
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
@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
@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
Thanks for the code
Awesome! I’ve been looking for this one.
Thanks you ZZZZZ!!
That just was what I was looking for.
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.
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.
Could any one tell us how to disable the “Back button” from the
Ie / FF
To disable back, you simply need to include this js code:
window.history.forward(1);
@ 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.
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.
to Basti - Thanks! Just what I needed
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?
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);
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 ?
Cheers for the code
I really, truly am glad I found this site. It has answered so many questions for me. I will be back. Thank You
Hello
Good code, Thank You
but problem to disable CTRL++ (107)
Who makes a zoom in IE7
Can any body help ?
// Internet Explorer// Internet Explorer// Internet Explorer
Hi
None of the above code works for Firefox 2.0.0.1.
Does anybody have idea how to get it work?
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();
}
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.
This site is truly a great resource thanks for all your hard work
I can find many things that I look for here! Thank you very much!
gr8 work guys.. finally i was able to disable refresh , backspace and ctrl + n
thanks
keep up the gudd work
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; }
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!
i am using ajax for autocomplete textbox but wen a i hit enter it submits the form…if any one could help me
THANKYOU zzzzzzzzzz and Slobodan! Everyone else only offered IE solutions! It works on my form and I’m only a beginner.
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.
[…] 38. Disable form submit on enter keypress […]
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; }
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
call it with [input onkeypress=’noenter(event);’ value=’xx’]
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
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
Thanks, this script helped me a lot. Awesome! Just what I was looking for
[…] 38. Disable form submit on enter keypress […]
[…] 38. Disable form submit on enter keypress […]
Excellent, i’ve been looking for a script like this for ages…!
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
Slobodan, good code.
I captured the event in the label
It works properly for all “Enter key” pressed into the form
Thanks
text omited in the last comment:
in the label…
form id=”form1″ name=”form1″ method=”post” onKeyPress=”return disableEnterKey(event)” action=”ins_form2.asp”
nice work, first time I googled something I needed and got what I needed straight away.
[…] 38. Disable form submit on enter keypress […]
Thanks for taking the time to share your hard work. It was just what I needed. Well Done!
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 ??
[…] 38. Disable form submit on enter keypress […]
Thanks for the script!
[…] 14、按回车键使form表单不能提交 […]
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!!!
just include this on your form tag…
like this
works fine on my application.
form id=”frmCreatePO” runat=”server” onkeypress=”return event.keyCode!=13″
[…] Disable form submit on enter keypress […]
[…] 38. Disable form submit on enter keypress […]
[…] 38. Disable form submit on enter keypress […]
[…] 38. Disable form submit on enter keypress […]
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