• Submit a Form in IE with Enter

    Jan 23 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 at 5:19pm on January 23, 2007

    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 at 12:13pm on January 30, 2007

    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 at 11:50pm on February 15, 2007

    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 at 5:23pm on February 20, 2007

    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 at 4:35pm on March 6, 2007

    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 at 4:24pm on March 7, 2007

    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 at 6:05pm on March 12, 2007

    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 at 10:23am on March 20, 2007

    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 at 10:38am on April 16, 2007

    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 at 8:21pm on April 19, 2007

    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 at 12:52am on April 22, 2007

    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 at 2:52am on May 5, 2007

    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 at 4:51am on May 7, 2007

    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 at 1:11pm on May 9, 2007

    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 at 9:34am on May 12, 2007

    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 at 4:56pm on May 21, 2007

    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 at 12:23am on May 28, 2007

    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 at 11:29am on June 29, 2007

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

    19. Nicholas at 6:01pm on July 16, 2007

    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 at 3:15pm on July 23, 2007

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

    21. Lasse Manson at 8:54am on July 31, 2007

    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 at 9:08pm on July 31, 2007

    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 at 9:58am on August 13, 2007

    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 at 11:05am on September 14, 2007

    This info helped me!
    Thanks.

    25. gogo at 10:42am on September 19, 2007

    /* 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 at 10:15am on September 23, 2007

    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 at 1:46pm on January 13, 2008

    <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 at 10:56pm on January 17, 2008

    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 at 4:52pm on January 22, 2008

    This is really cool thank you

    30. Javed shaikh at 12:48am on February 6, 2008

    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 at 2:19pm on February 21, 2008

    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 at 3:20am on March 11, 2008

    awesome thanks!

    33. kernelcored at 3:22am on March 12, 2008

    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 at 10:05am on March 17, 2008

    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 at 3:31am on April 7, 2008

    thanks for the jquery code. works great

    36. Brandon at 1:23pm on April 20, 2008

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

    37. Rich Lovelock at 11:04am on July 8, 2008

    Many thanks, the javascript functions work great for me.

    38. andy parker at 9:28am on July 14, 2008

    brilliant. that filled a hole

    39. vikram at 8:45am on August 9, 2008

    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 at 2:21pm on September 10, 2008

    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 at 1:53pm on November 20, 2008

    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 at 4:18am on March 3, 2009

    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 at 1:49am on March 20, 2009

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

    44. Riccardo at 8:54am on March 26, 2009

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

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

    45. CK Ng at 4:31am on May 13, 2009

    I ended up with

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

    46. Jeff at 12:05am on May 30, 2009

    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 at 4:54pm on June 17, 2009

    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 at 10:23am on July 21, 2009

    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 at 7:01am on August 18, 2009

    comment 45 worked for me! Gj!

    50. Commander at 5:49pm on August 30, 2009

    @ 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 at 9:22am on February 19, 2010

    Great article. Very helpful to me.

    52. Shane Larson at 1:12pm on February 24, 2010

    Works great!  thanks for the tip.

    53. Kawika at 1:04pm on March 7, 2010

    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 at 11:13am on March 19, 2010

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

    55. Noor at 5:32am on April 7, 2010

    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 at 5:49pm on April 26, 2010

    Works a treat... thanks!

    57. aleanjos at 8:19pm on May 6, 2010

    thanks!

    58. Blessed Tabvirwa at 3:59am on May 20, 2010

    Thanks a lot, works perfectly on my site.

    59. dipali at 2:59am on May 27, 2010

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

    60. Ernesto Koehler at 5:42am on May 28, 2010

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

    61. lobo at 7:52am on June 11, 2010

    add this to your form:

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

    62. organicodd at 3:38am on August 9, 2010

    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 at 10:39pm on September 14, 2010

    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 at 3:14am on September 23, 2010

    Good Solution.. Thank you so much..

    65. Joe at 11:35am on November 19, 2010

    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 at 9:03am on November 29, 2010

    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 at 10:16am on February 11, 2011

    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 at 9:02am on April 5, 2011

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

    69. Eric at 9:04am on April 5, 2011

    OOps.... not FF but Chrome!

    70. Guilherme at 10:25am on August 3, 2011

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

    71. paul at 2:06pm on August 3, 2011

    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 at 11:56am on August 25, 2011

    Sweet and easy: done same as Jay@48.
    Your rule rules, Jesse!

    73. yauhen at 5:33am on August 29, 2011

    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 at 3:34am on December 27, 2012

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

    Commenting is now closed. Come find me on Twitter.