Coding with Jesse

Submit a Form in IE with Enter

January 23rd, 2007

Usually, you want to be able to submit a form, like a login or search, just by hitting enter. But sometimes it doesn't work.

Firefox will always let you submit any form by pressing Enter, but Internet Explorer is a little bit picky. I figured out a generalised rule of when it won't work:

There is more than one text/password field, but no <input type="submit"/> or <input type="image"/> is visible when the page loads.

This rule has the following interesting consequences:

  • If you just have a <button/>, hitting enter won't submit the form.
  • Hiding submit buttons by using display:none, positioning them off the page, hiding them inside an overflow:hidden, or any other method will break the enter-to-submit functionality.
  • If a form is hidden when the page loads and is displayed using JavaScript, the enter-to-submit will be broken.

It appears that Internet Explorer scans the page at load time and figures out which submit buttons are visible, then attaches the enter-to-submit functionality to those forms.

To fix these scenarios, you can use the following JavaScript:

function addInputSubmitEvent(form, input) {
    input.onkeydown = function(e) {
        e = e || window.event;
        if (e.keyCode == 13) {
            form.submit();
            return false;
        }
    };
}

window.onload = function() {
    var forms = document.getElementsByTagName('form');

    for (var i=0;i < forms.length;i++) {
        var inputs = forms[i].getElementsByTagName('input');

        for (var j=0;j < inputs.length;j++)
            addInputSubmitEvent(forms[i], inputs[j]);
    }
};

(Of course, it's better if you use addDOMLoadEvent instead of window.onload and addEvent instead of onkeydown.)

If you use jQuery, you can just write:

$(function(){
    $('input').keydown(function(e){
        if (e.keyCode == 13) {
            $(this).parents('form').submit();
            return false;
        }
    });
});

The return false is rather important in Internet Explorer, because it prevents that beep that you might hear if you hit return. The beep is saying "you can't hit enter here!", but return false cancels the key press and therefore the browser won't warn.

Update: As Eric Lentz pointed out, my previous code would submit a form when hitting enter in a textarea. I fixed the solution so the onkeydown event is added to <input> elements only.


Comments

1 . Greg on January 23rd, 2007

Greg

I've recently encountered this problem on a client project. How can I implement a fix in a .NET environment, which allows only one form element per page regardless of the number of submit buttons?

2 . Tom Freeman on January 30th, 2007

Tom Freeman

Hi,

Interesting to read your article, I had this problem on a site I was developing. It's something that I would probably have just said 'oh well nevermind' but my boss was keen for me to get to the bottom of it and make enter submit the form. I ended up solving the problem and i'm not sure what the problem was, but I think it was due to the fact I had more than 1 form on the page... I think possibly the first form wasn't closed before the second started. However both forms were also hidden so it may be that which caused the problem, however I don't think I put in any javascript solution. I think I just made sure the code was correct and it worked ok...

Tom

3 . Nitesh on February 15th, 2007

Nitesh

Very Interesting ! Tried it out on IE and FireFox . works perfectly. However i realised one more thing .. if u have a select box , and ur focused on it , enter does not submit the form !!!

No reason why .. it doesn't work on IE or Firefox .. works for all other form elements but <select> ...

Strange !!

4 . Eric Lentz on February 20th, 2007

Eric Lentz

There is a problem with this solution. If you have a textarea you may need that enter key, as I did, without a form being submitted. My solution is camouflage.

Here is my button:
<input id="subbut" type="submit">

The background color of the form upon which it resides is #80bce0 (not my choice).

Here is my CSS for the button:

input#subbut {
color: #80bce0;
background-color: #80bce0;
border: none;
width: 1px;
height: 1px;
}
The 1px button is not visible on the form. When it was bigger I could see an outline of it when I hit enter which wasn't desirable. Making it really small got rid of that. I know where it is and it is very difficult for me to "accidentally" hit it, though I am able to with perseverance. A user not knowing it was there would have a 1 in 512,000 chance of hitting it on a form 500 pixels high and a 1024x768 pixel resolution. I don't expect anyone will notice it is there.
Tested with IE 6 and Firefox 2.0

5 . Bryan Cox on March 6th, 2007

Bryan Cox

For the SELECT issue, the code above wouldn't work, because it's only affecting INPUT tags, but even if you modify it to affect SELECT, it doesn't work. But there's a workaround (ex. using jQuery):

$(function(){
$('select').keydown(function(e){
if (e.keyCode == 13) {
$(':submit').click();
return false;
}
});
});

Instead of calling submit() on the form, you can call click() on the submit button, and it works from a SELECT...

6 . Rob Bygrave on March 7th, 2007

Rob Bygrave

Thanks for this article :) I have found it very useful.

I had the opposite requirement - stopping the ENTER key from automatically submitting the form. As I understand it a good approach (is there a better one?) is a variation on what you have done here.

// using jQuery ...

$(function(){
$('input.field').keydown(function(e){
if (e.keyCode == 13) {
return false;
}
});
});

7 . travos on March 12nd, 2007

travos

I ran into a case in which I wanted to submit a form, but process other instructions at the same time, so my solution to add a little more flexibility:

document.body.onkeydown = function(event){
tw_textfieldenter("form.var.something=1;form.submit();", event);
};

//also add firefox/moz based browser compatability
function tw_textfieldenter(stuffToDo,e){
var keycode;
if (window.event) keycode = window.event.keyCode; //ie
else if (e) keycode = e.which; //ff

if (keycode && keycode == 13){
eval(stuffToDo);
return false; //removes ie submit beep
}
}

Given, this assumes that you have a single form on a page. document.body could be replaced with whatever node or input control.

8 . JF Lanouette on March 20th, 2007

JF Lanouette

Well the real solution is to have only one submit button on the form, the IE will make it the default... But be aware that most of the time programmers want to have more then one button able to post the form in that case they will have to add javascript to handle the other button (else then the default one)

it's pretty easy once you understand how ie works

9 . Isaac Tewolde on April 16th, 2007

Isaac Tewolde

There is another wrinkle.

If you are depending on the button name & value being submitted on enter, then you will have problems in IE.

The button name and value are sent only when the button is clicked, otherwise the form is submitted without this information. A workaround I usually do is to have the information I need to be inside hidden fields instead of relying on the button.

10 . JB on April 19th, 2007

JB

I found the form was being submited but the submit filed was not included int the get array. I added a hidden input with the same name as the submit. This will work if javascrit is disabled.

11 . Etienne Mac on April 22nd, 2007

Etienne Mac

And just for completeness (for us Mac folks), you should also test for charcode '3' as well as '13'. '3' is the ENTER key on a Mac on the numeric pad, which within the context of a FORM will emulate the behaviors of the RET key (charcode 13).

12 . Puppet on May 5th, 2007

Puppet

If you have server side scripting tools available, like php, then you could use it to check if the text field was posted containing data and not check solely if the button name itself was posted.

?php
if (!empty($_GET) && $_GET['value_name']) {
// take an action upon success
} else {
//show error msg, ignore request, etc.
}
?>

A great example is a site a friend uses the services of ( http://www.4RemoteSupport.com - www.4RemoteSupport.com ) has two forms on their main page. I inquired as to how they overcame the IE problem of having two forms on the same page and the user hitting the enter key. They were nice enough to reply with some useful information.

I hope this information may help someone with a similar problem. At least it points out that there are additional methods to fix this sort of problem (... I mean feature not problem) besides javascript and CSS.

13 . addiktion on May 7th, 2007

addiktion

You would think IE would jump on the band wagon to fix this. It's annoying. Always gotta patch things to make them work with Microsoft~

14 . Nathan Strong on May 9th, 2007

Nathan Strong

THANK YOU ISAAC!

I've been pulling my hair out trying to figure out why my search button works in every browser except IE.. and you nailed it right on the head.

15 . Luke on May 12nd, 2007

Luke

Just a little comment here about IE in general. For such a large company as Microsoft to create such a terribly "difficult" browser as IE, is beyond all sense. There is this issue of submit buttons, but also the issue of flash files needing to be activated, then also the php include() function not working on pages with utf-8 encoding, and the list goes on. No wonder I use Firefox and I would recommend everyone to do so.

16 . Charlie Arehart on May 21st, 2007

Charlie Arehart

Jesse, I found your blog entry while looking into this. I noticed only today for the first time that the enter key wasn't submitting if there was more than one input type=text without a submit button.

But I have to question your assertion (and the comments above) about this being an IE-only problem. I find it to be true as well in Firefox 2.0.0.3.

As soon as I add a submit button, or remove the second text field, the submission on enter works again.

17 . Carol on May 28th, 2007

Carol

Umm, this might sound silly, but I actually DON'T want my form to submit on pressing enter. I find that some people (when not really thinking) press enter to go to the next text input field on the next line, and submit the form accidentally, prematurely. Can anyone tell me how to disable this feature and stop this from happening?

18 . IE/Firefox on June 29th, 2007

IE/Firefox

It's not a bug, it's a feature...
http://www.devside.net/blog/linux-windows-bug-feature

19 . Nicholas on July 16th, 2007

Nicholas

I've got one weird situation.
I have a form with two submit buttons. One is delete and another is update. I am using php.
Also I am using $_SERVER['PHP_SELF'], so that it will call itself for update. For form code goes like this.

<input name="update" type="submit" value="Update" />
<input name="delete" type="submit" value="Delete" />

In server side code goes like this

if(isset($_POST['update']))
{
//update
}

if(isset($_POST['delete']))
{
//delete
}

Now: Here is the problem. This code works perfectly in Firefox but not in IE. I even used javascript to submit form instead but it did not worked.

ANY HELP WILL BE GREATLY APPRECIATED.

20 . mem on July 23rd, 2007

mem

Carol to stop that from occuring, validate the form. :p

21 . Lasse Manson on July 31st, 2007

Lasse Manson

Hey guys,

I find when it comes to forms, its all a matter of opinion. Firstly I use javascript to validate all the fields, alerting if incorrect values are left out. Then I additionally check the value via php, sending them back to the prior page and retaining their original values.

Time consuming, but when you work with databases, bookings, and finnicky things. You need to be carefull.

By the way to stop the enter button working:

//Get the submit, this is important that it points
$submit = $_POST['submit'];

if (isset($submit)){
//code to execute }

<!--THE FORM-->
<form action blah blah>
<input>
<input>
<input type="submit" name="submit" value="submit">
<!-- this form wont submit on enter (with ie) unless there is a
<input type="hidden" value="submit"> -->

but hell who knows?

22 . Mario on July 31st, 2007

Mario

Thank you Isaac Tewolde,

you gave us the simplest key: In turn of checking on the submit var check on a hidden var included in the form.

23 . hello on August 13rd, 2007

hello

when using a password field, i noticed firefox is not activating that "password confirm" window. so i restricted that jquery function just to MSIE.

if($.browser.msie) {
$(function(){
$('input').keydown(function(e){
if (e.keyCode == 13) {
$(this).parents('form').submit();
return false;
}
});
});
}

24 . deepaohms on September 14th, 2007

deepaohms

This info helped me!
Thanks.

25 . gogo on September 19th, 2007

gogo

/* A tiny improvement / modification if you need the form to be sent also when choosing other fields like select boxes (in firefox it made the form get submitted also for ticking any check box or radio button too!!) all you need to do is to replace the original code presented here by this one: */

function addInputSubmitEvent(form, input) {
input.onkeydown = function(e) {
e = e || window.event;
if (e.keyCode == 13) {
form.submit();
return false;
}
};
}

window.onload = function() {
var forms = document.getElementsByTagName('form');

for (var i=0;i < forms.length;i++) {
var inputs = forms[i].getElementsByTagName('input');
var selects= forms[i].getElementsByTagName('select');

for (var j=0;j < inputs.length;j++)
addInputSubmitEvent(forms[i], inputs[j]);

for (var j=0;j < selects.length;j++)
addInputSubmitEvent(forms[i], selects[j]);
}
};

/* thanks for the creator of this code hope this helps others too :)) */

26 . Bart on September 23rd, 2007

Bart

Hey,

I spend my time working around the hidden submit button problem and found a solution that works in both browsers:

<div class="hidesubmit"><input type="submit"></div>

and in the style section/file:

div.hidesubmit {
border: none;
width: 0px;
height: 0px;
overflow: hidden;
}

27 . prabhat singh on January 13rd, 2008

prabhat singh

<input style="border:0; width:0; height:0" type="text" size="0" maxlength="0" />


Add this before input="submit" , and Enter key works in MSIE.

28 . harpster on January 17th, 2008

harpster

Thanks to the info on this page I solved the problem that was kicking my rear. One one page I had a form with several input fields and a Find and Find All button and when I hit enter it submitted. One the other page I had only one input field and one button and it would not submit. When I looked at the $post_array the text in the input box text was always returned but the "find" value was only returned if I hit the find button. I reduced the code to a few lines and it still had this problem (yes I like the enter button to submit). When I read something about it won't work with only one button (IE6 is really stupid) I just added a hidden button with the same find value and it works in all browsers tested so far so thanks much for the tip!

would not submit with enter key:
<input type="submit" name= "find" value= "Find"/>

adding the hidden field before the find button worked:
<input type="hidden" name="find" /><input type="submit" name= "find" value= "Find">

29 . Web Tasarım on January 22nd, 2008

Web Tasarım

This is really cool thank you

30 . Javed shaikh on February 6th, 2008

Javed shaikh

I have one problem with IE.
In my form i have only one text field and one submit button,
when i enter something in text field and press enter key then it
doesn't submit the form, it just refresh the page. Instead of pressing enter key if i click on submit button it works fine.
I have found the solution for this problem, but i want to know perfect solution for this. Just try it out in IE.

31 . Jerbear on February 21st, 2008

Jerbear

You may have noticed that calling <em>form.submit()</em> in IE doesn't call the code that is located the in the form's <em>onsubmit</em> attribute. Another really cool feature!

To remedy this you need an extra line:

if (e.keyCode == 13) {
$(this).parents('form').attr("onsubmit")();// run onsubmit stuff in IE
$(this).parents('form').trigger('submit');
return false;
}

32 . george on March 11st, 2008

george

awesome thanks!

33 . kernelcored on March 12nd, 2008

kernelcored

I did as JB (comment #10) did and it works !
Btw, nice workaround. Google takes me right to this blog and my problem solved ^_^

34 . James Beck on March 17th, 2008

James Beck

I have found this a problem as ie doen't always include submit in the GET / POST array, and then you may use something like...

if (isset($_GET['submit'])
{

}

I simply check for the submission of compulsary input fields rather than the submit element in any given form.

35 . Svilen Sabev on April 7th, 2008

Svilen Sabev

thanks for the jquery code. works great

36 . Brandon on April 20th, 2008

Brandon

My problem was that the "submit" button wasn't being passed.

37 . Rich Lovelock on July 8th, 2008

Rich Lovelock

Many thanks, the javascript functions work great for me.

38 . andy parker on July 14th, 2008

andy parker

brilliant. that filled a hole

39 . vikram on August 9th, 2008

vikram

hi guys
I have been stuck with this issue for 3+ hrs now..can anyone please help?

my page #s on a search results page trigger a function that submits the page's search form.

this is how I generate the page #:
echo '&nbsp;&nbsp;<a href="javascript:void(0);" onclick="return Paginate('.$i.');">'.$i.'</a>';
where $i is in a loop.

This is the Paginate function
function Paginate(p)
{
//alert("valu " + document.getElementById('formSearch').current_page.value);
var frm = document.getElementById("formSearch");
var btnSubmit = document.getElementById("btnSearch");
frm.current_page.value=p;
//document.formSearch.submit();
frm.submit();
}

My form is declared as:
<form action="main.php" method="post" id="formSearch" name="formSearch">

And the submit button is declared as:
<input name="btnSearch" type="submit" id="btnSearch" value="Search">
(just one submit button).

Now in FF, it works fine. In IE, it seems to call the Paginate function since I can see the popup window (the alert call in the function)...but the form wont submit.

Funny thing is.. you click the page number.. form won't submit immediately.. but you click on another link or the submit button yourself, and it will suddeny show the refreshed page with the new page number.

someone please help with this IE wackkiness ?

thanks guys

40 . H. Ackerman on September 10th, 2008

H. Ackerman

I just ran across this oddity...

Anyhoo, IE seems to submit when there's a "submit"-type input, but not when there's an "image"-type input.

Except on a different page, either works. Or doesn't work. Based on my investigation, I think it has something to do with whether or not you've set the clock properly on your VCR. If you're too young to have a VCR, then you're SOL. Sorry kids.

41 . Fernando on November 20th, 2008

Fernando

Hi guys,
I found this post very interesting, nice work! But I figured out the 'button' element indeed works on IE6 by simply hitting enter button (with Javascript disabled) even when focus isn't on it. I'm very new on this topic, so I wanted to know if there is any reason that forces you to use the 'input' element instead of using a 'button'?
thank you !

42 . john on March 3rd, 2009

john

function addInputSubmitEvent(form, input) {
input.onkeydown = function(evt) {
var evt = (evt) ? evt : event
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode == 13) {
form.submit();
return false;
}
};
}
window.onload = function() {
var forms = document.getElementsByTagName('form');

for (var i=0;i < forms.length;i++) {
var inputs = forms[i].getElementsByTagName('input');

for (var j=0;j < inputs.length;j++)
addInputSubmitEvent(forms[i], inputs[j]);
}
};

43 . Shubhangi on March 20th, 2009

Shubhangi

Thanks prabhat It is very useful info
so thanks much for the tip!

44 . Riccardo on March 26th, 2009

Riccardo

Thanks, this one works for me on Firefox, IE6 and Ie7

26. Bart at 4:15pm on September 23, 2007

45 . CK Ng on May 13rd, 2009

CK Ng

I ended up with

if ($.browser.msie) {
$('input, select').keydown(function(e){
if (e.keyCode == 13) {
$(':submit').click();
return false;
}
});
}

46 . Jeff on May 30th, 2009

Jeff

IE doesn't like it when the input type=submit and name=submit.

Quickest solution is to remove name=submit from the submit input, and set up a hidden field with name=submit and the same value of the submit button.

47 . Jin on June 17th, 2009

Jin

Thank you.. This is very helpful. The page I am working in did not submit login only on IE, while it was working fine in firefox and chrom.

48 . Jay on July 21st, 2009

Jay

Thanks for the input ... I added an image to my form with the following code:

<input type="image" style="width:0px;height:0px"/>

And "submit on enter" works like a charm.

49 . noff on August 18th, 2009

noff

comment 45 worked for me! Gj!

50 . Commander on August 30th, 2009

Commander

@ 48.

Thanks, it works in IE, however FF 3.5 displays a string instead of the 0px image, something localized like: Submit Data.

To prevent this, add the alt-attribut e.g. alt="" to it and its fixed for FF as well.

51 . AngloPolish on February 19th, 2010

AngloPolish

Great article. Very helpful to me.

52 . Shane Larson on February 24th, 2010

Shane Larson

Works great! thanks for the tip.

53 . Kawika on March 7th, 2010

Kawika

Thanks! The fact that IE doesn't include the submit button's data in the POST array when you submit the form using enter was breaking my script, and thanks to this entry I fixed it. Thanks!

54 . AngloPolish on March 19th, 2010

AngloPolish

Good article, but wat i want I found in one of the comments.

55 . Noor on April 7th, 2010

Noor

How about when user has the option for either hitting the Submit button as well as hitting enter to submit the search form ?

Any ideas on that ?

56 . Terry on April 26th, 2010

Terry

Works a treat... thanks!

57 . aleanjos on May 6th, 2010

aleanjos

thanks!

58 . Blessed Tabvirwa on May 20th, 2010

Blessed Tabvirwa

Thanks a lot, works perfectly on my site.

59 . dipali on May 27th, 2010

dipali

Thanks a ton,Jesse Skinner. It works fine on my site. Great job ...

60 . Ernesto Koehler on May 28th, 2010

Ernesto Koehler

Thank You a lot! prabhat singh's easy solution works great!

61 . lobo on June 11st, 2010

lobo

add this to your form:

<div style="border:0;width:0;height:0;overflow:hidden;"><input type="submit"/></div>

62 . organicodd on August 9th, 2010

organicodd

hi,

encoutered the same problem, though I could fix it by hidding the submit button but does not work with IE6 and maybe more

here is my solution:


/**
* This function parse a form and attach an event on each accurate element so that the form is submitted when the enter key is pressed.
* It is used to allow us to use an image or a link to submit a form, as it fixes the problems with the way browsers handle
* automatic submission of forms when enter key is pressed. These problems are:
* - Mozilla will not submit a form if no submit button is present
* - IE will not submit the form if no visible submit button is present (display:none or visibily:hidden do not work)
*
*/
function submitFormOnKeyPressEnter(someForm) {

for (i=0 ; i<someForm.length ; i++){


if (someForm[i].type == 'text' ||
someForm[i].type == 'radio' ||
someForm[i].type == 'checkbox' ||
someForm[i].type == 'select-one' ||
someForm[i].type == 'password') {

jQuery(someForm[i]).keypress(function(e){
var keycode;
if (window.event) {
keycode = window.event.keyCode;
} else if (e) {
keycode = e.which;
}
if(keycode == "13"){ /* user pressed enter !*/
alert("enter!");
someForm.submit();
}
});
}
}
}

this function is called like this:

submitFormOnKeyPressEnter(document.forms['myFormName']);

tested with mozilla and ie

63 . Bronius on September 14th, 2010

Bronius

Unbelievable. Thanks for this post-- spot on, and fixed an issue a team-member discovered in IE8.

To the 2007 comments about focus on SELECT: Hitting enter while a select list has focus has never submitted a form in IE. Probably they allow for better keyboard nav and selecting items..?

-Bronius

64 . Manimala on September 23rd, 2010

Manimala

Good Solution.. Thank you so much..

65 . Joe on November 19th, 2010

Joe

I had this same issue with a form that was hidden on page load. I solved it by using javascript to hide the form after page load. Using enter now submits the form in IE 8.

66 . Jey on November 29th, 2010

Jey

Thanks Harpster. U gave very useful to all.

within the form coding..

<input type="submit" name="login" value="login">

this submit coding never execute in IE browser..

In front of this code..we will use hdiden values..

For example...

<input type="hidden" name="login" value="login">
<input type="submit" name="login" value="login">

Like above that...

Really above all points are very usefull to me..
Thanks lot guys

67 . Riya on February 11st, 2011

Riya

This was very helpful I was stuck with IE nit submitting my form since jquery was hiding my submit button to apply some styles.
now works perfect. Once more Thank You.

68 . Eric on April 5th, 2011

Eric

I had to remove 'return false' for it to work in FF.

69 . Eric on April 5th, 2011

Eric

OOps.... not FF but Chrome!

70 . Guilherme on August 3rd, 2011

Guilherme

Thanks a lot! It worked flawlessly on IE6, IE8, Firefox 5 and Chrome 12!

71 . paul on August 3rd, 2011

paul

Seriously? People still want forms to submit on "enter"? Many here touched on the reasons why you don't want to submit on enter, and those reasons are more valid and hold true than the reasons for using the enter key to submit a form.

72 . Marco Faustinelli on August 25th, 2011

Marco Faustinelli

Sweet and easy: done same as [email protected]
Your rule rules, Jesse!

73 . yauhen on August 29th, 2011

yauhen

Jquery UI dialog. Inside which is form. Of course dialogs will be hidden by default. No of the solutions with input hidden (66),
input image 48 works for IE8

74 . Marcel on December 27th, 2012

Marcel

Thank you for this blog!
Was searching quite long to fix my problem with onenter and IE.
Keep up the good work.

Comments are closed, but I'd still love to hear your thoughts.