48

I have the following HTML/JS/jQuery Code. This code represents a login form that is presented modally to the user to allow them to login. The problem is, when I hit enter, the form does not seem to execute the "onsubmit" event. When I click the button as the bottom of the form (which has virtually the same code as the onsubmit event), it works perfectly. I am wondering if anyone can tell me why this form isn't submitting..? Any assistance would be appreciated.

jQuery Code to Show Login Modal:

showDivAndFocus('loginModal','loginaccount'); 

function showDivAndFocus(v,t){

    if (api)
        if (api.isOpened)
            api.close();

    api = $('#'+v).overlay({
        mask: {color: '#000000'}, 
        top:'0px',
        api: true,
        autoScrollToActive: false,
        autoScrollOffset: 0 
    }).load();

    document.getElementById(t).focus();
}

HTML Code

<div class="modal" id="loginModal">
    <h2>User Login</h2>
    <br />

    <form action="javascript:void(0);" onsubmit="return(doLogin());"  name="loginForm" id="loginForm">
        <table width="95%" cellpadding="4" cellspacing="4">
        <tr>
        <td class="regw" align="left"><b>Account Number:</b></td>
        <td class="regw" align="left"><input type="text" maxlength="10" size="10" name="loginaccount" id="loginaccount" /></td>
        </tr>

        <tr>
        <td class="regw" align="left"><b>Username:</b></td>
        <td class="regw" align="left"><input type="text" maxlength="20" size="20" name="loginusername" id="loginusername" /></td>
        </tr>

        <tr>
        <td class="regw" align="left"><b>Password:</b></td>
        <td class="regw" align="left"><input type="password" maxlength="20" size="20" name="loginpassword" id="loginpassword" /></td>
        </tr>  

        <tr>
        <td class="regw" align="left"><b>Remember Me:</b></td>
        <td class="regw" align="left"><input type="checkbox" name="loginremember" id="loginremember" /></td>
        </tr>  

        <tr><td colspan="2">
            <div>  
                <center>
                    <table><tr><td width="50" valign="middle">
                        <div id="loginLoading" style="height:24px;width:24px;"></div>   
                    </td><td>
                        <button onclick="doLogin();" type="button" class="ok">Submit</button>
                    </td><td>
                        <button onclick="api.close();" type="button" class="cancel">Cancel</button>
                    </td><td width="50">&nbsp;</td></tr></table>
                </center>
            </div>
        </td></tr> 
        </table>
    </form>
</div>

AJAX Call

function doLogin(){
    var ajax = getXmlObject();
    var f = getFormVariables();
    var url= '/login.php?f=' + encodeURIComponent(f);
    if (ajax.readyState == 4 || ajax.readyState == 0) {
        ajax.open("POST", url, true);
        ajax.onreadystatechange = function () {
            if (ajax.readyState == 4) {
                var a = ajax.responseText;
                if (a=="OK"){...} else {...}
            }
        };
        ajax.send(null);
      }
      return false;
 }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Dutchie432
  • 28,798
  • 20
  • 92
  • 109

9 Answers9

66

I was struggling with this same issue; one of my forms was submitting when pressing "enter" in the text fields with no problem; another, similar, form on the same page wouldn't submit at all, for the life of me.

Neither field had a submit button, and neither was using javascript to do any submission.

What I found, is that when there is only a single text field in a form, pressing 'enter' in the text field will automatically submit; but if there is more than one (regular (i.e. single-line) text input) field, it does nothing, unless there is also some kind of 'submit' button.

Apparently this is part of the HTML 2.0 specification:

When there is only one single-line text input field in a form, the user agent should accept Enter in that field as a request to submit the form.

An old, but apparently still valid, and interesting, further discussion here.

... evidently meant as a convenient way to submit simple queries, but reducing the risk, on a complex form, of prematurely submitting it while trying to fill it in. Numerous browser implementers (e.g Netscape, Opera, various versions of Lynx,...) followed this advice, though it seems with slightly different interpretations.

I made a JSFiddle to demonstrate. As far as I can tell (lazily just testing with Chrome), the form will submit on "Enter" if there's only one text field, or if there's a submit button, even if it's hidden.

(EDIT: I later found that it also does seem work if there are other input fields which are not a regular, single-line text input ... e.g., textareas, selects, etc. -- thanks to @user3292788 for that information. Updated the JSFiddle to reflect this).

<h2>Form with one text field only, no submit button</h2>
<p>Seems to submit automatically when pressing 'enter' in the first text field</p>
<form action="" method="post">
  <div>
    <label for="pt-search-input">Search</label>
    <div>
      <input name="term" type="text" placeholder="Example: budapest amsterdam" /> <a href="#pt-search-bar">cancel</a></div>
  </div>
</form>

<h2>Form with two text fields, no submit button</h2>
<p>Won't submit when pressing 'enter' in the forms ...</p>
<form action="" method="post">
  <div>
    <label for="pt-search-input">Search</label>
    <div>
      <input name="term" type="text" placeholder="Example: budapest amsterdam" />
      <input name="term2" type="text" placeholder="Example: budapest amsterdam" /> <a href="#pt-search-bar">cancel</a></div>
  </div>
</form>



<h2>Form with two text fields and a submit button ...</h2>
<p>Now it submits with 'enter' key</p>
<form action="" method="post">
  <div>
    <label for="pt-search-input">Search</label>
    <div>
      <input name="term" type="text" placeholder="Example: budapest amsterdam" />
      <input name="term2" type="text" placeholder="Example: budapest amsterdam" /> <a href="#pt-search-bar">cancel</a>
      <input type="submit" />
    </div>
  </div>
</form>

<h2>Form with two text fields and a HIDDEN submit button ...</h2>
<p>Seems to work, even with submit hidden ...</p>
<form action="" method="post">
  <div>
    <label for="pt-search-input">Search</label>
    <div>
      <input name="term" type="text" placeholder="Example: budapest amsterdam" />
      <input name="term2" type="text" placeholder="Example: budapest amsterdam" /> <a href="#pt-search-bar">cancel</a>
      <input type="submit" />
    </div>
  </div>
</form>


<h2>Form with no action or method attribute, HIDDEN submit button ...</h2>
<p>Even this seems to work.</p>
<form>
  <div>
    <label for="search-input">Search</label>
    <div>
      <input name="term" type="text" placeholder="Example: budapest amsterdam" />
      <input name="term2" type="text" placeholder="Example: budapest amsterdam" /> <a href="#pt-search-bar">cancel</a>
      <input type="submit" />
    </div>
  </div>
</form>

<h2>Form with multiple fields, but only one text input, no submit button.</h2>
<p>This seems to work as well.</p>
<form action="" method="post">

  <p><input type="text" ></p>

  <textarea name="" id="" cols="30" rows="10"></textarea>

  <p>
    <select name="" id="">
      <option value="">Value</option>
    </select>
   </p>
</form>
Aaron Wallentine
  • 2,318
  • 24
  • 22
  • 1
    I think that you missed the **one single-line text input field** precision. The form is even so submitted with more than one field if others fields are not _as said_ single-line text input field. You can check this quick [JSFiddle](https://jsfiddle.net/9L4oxrg2/). By the way, your answer is the right one and helped me to solve my problem. – user3292788 May 31 '16 at 00:54
  • @user3292788 oh, ok. Yeah, I hadn't noticed that, because mine were both regular text input fields. Didn't think to try with other types of fields. : ) Thanks for the additional info. I updated the answer to reflect this. – Aaron Wallentine Jul 11 '16 at 23:48
  • I don't think this is true anymore, at least for HTML5. – Dan Apr 24 '23 at 17:05
45

You have two choices:

  1. Create an event handler for the enter button and add it to your bindings.
  2. Use an <input type=submit> in the form somewhere, which is what gets the automatic Enter Key behavior you're after.
g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
  • 1
    I don't believe this to be true.. The form should submit either way when enter is pressed. I have another form doing virtually the same thing. It's not being displayed 'modally' and that's the only real difference I can see. For sure, however, neither form has a submit button or onkeyX events. – Dutchie432 Nov 16 '10 at 16:58
  • 4
    I'd go for the `` because it's more semantically correct. – Timo Willemsen Nov 16 '10 at 16:58
  • 2
    @Dutchie432 - As I understand it (and I'd love someone to correct me if I'm mistaken) the behavior you're getting on the other form is either erroneous, or somehow focus is transferring to one of your submit buttons before you press enter. HTML Forms are only supposed to submit via the Enter Key when using ``. If you actually have focus on a button though, it's possible the enter key will 'click' it for you. – g.d.d.c Nov 16 '10 at 17:24
  • I've done this on virtually every form I have on this website, and now that I set it up on a JSFiddle, it doesn't work... Hrmmm.. – Dutchie432 Nov 16 '10 at 17:36
  • Honestly, I can't seem to figure out why it works with some forms, and not others. Odd! – Dutchie432 Nov 16 '10 at 18:41
  • @Dutchie432 - I'm still leaning toward it being related to focus on your buttons, but I'm not certain. A quick Google Search brings up a ton of similar quandaries. This one is a great example: http://www.webdeveloper.com/forum/showthread.php?t=52300. You'll notice the first question asked of the poster is "Do you have a submit button in your form?" That's the standard requirement for the Enter Key to submit the form. – g.d.d.c Nov 16 '10 at 20:51
  • I totally get it.. Im just STILL trying to figure out what makes my other forms submit then. – Dutchie432 Nov 23 '10 at 22:00
  • I picked this as the winner because it seems to be, in fact, the case as my stand-alone examples exhibit exactly this behavior. I have a handful of forms that DO function without a submit button (only `` objects and no events in the textboxes. – Dutchie432 Nov 24 '10 at 13:38
  • @Dutchie432 - It's definitely odd that others work, but going with the semantically correct approach to guarantee the behavior is probably your best option. Thanks for the accepted answer! :) – g.d.d.c Nov 24 '10 at 15:37
  • 28
    Just a note: if a form doesn't have a submit button (either `` or ``) [it will only auto-submit on Enter when it's got one text input](http://www.alanflavell.org.uk/www/formquestion.html). Forms *with* submit buttons *should* submit on Enter regardless of the number of text inputs (although that isn't happening on a form of mine right now and I don't know why). Also, if your ` – Paul d'Aoust Mar 11 '14 at 20:19
  • 2
    To clarify on the comment made by @Pauld'Aoust - the `[Enter]` will only work if there is *only* one text input, not one or more. – xyhhx Aug 28 '16 at 15:40
6

It can also come from a javascript bind to a <button> in your form. For exemple, if you have

<button id='button'>Reset</button>
<span id="textToReset">some info</span>

<script type="text/javascript">
$('#button').bind('click', function(){  
    $('#textToReset').text('');     
    return false;
})
</script>

Your Enter button will be caught somewhere by the return falseand your form won't submit under Enter key. The correct way is to specify that the <button> ACT as a button. This way :

<button id='button' type="button">Reset</button>

and drop the return false you've putted there to prevent that button from submitting a form. ;-)

For the sake of learning, <button> type is by default submit. If you want them to act as control for your form, you must specify the type="button" or type="reset" See w3.org about it

DColl
  • 185
  • 2
  • 14
5

Just in case someone makes the same mistake as me and also comes here looking for an answer:

If you have two (or more) submit buttons1 in your form, hitting enter will only trigger the first submit and not the second.


1 as indicated by @paul-daoust in his comment on the answer of @g-d-d-c: Both <input type=submit> and <button type=submit> will work as a submit button

yaba
  • 829
  • 7
  • 11
2

If you have correct input-submit-button but use (click) event on that button, it will not trigger it on enter. It will submit form but not trigger click event on button, obviously. Putting functionality to form itself and it's submit event will make it work.

Workion
  • 37
  • 4
  • Please elaborate on your answer, also keep in mind that your answer should be different from the ones already posted. Post some example code and explain how your code is different from the others. – cloned Sep 12 '19 at 11:41
  • I would also appreciate elaboration. You're (perhaps) talking about what happened to me (even though my form is not bound on click but submit: `$('#myForm.on('submit',function(e){e.preventDefault();$.ajax({...});});`). Click on ` – s3c Dec 11 '19 at 13:38
  • typo: `$('#myForm').on('submit',function(e){e.preventDefault();$.ajax({...});});` – s3c Dec 11 '19 at 13:45
1

When you have more than one button specified in your form, if they dont have the attribute type specified but they have a tabindex with higher precedece, the first of those buttons will be triggered them before thebutton[type=submit]. Therefore, you should add the type=button to such buttons. Ex.:

<!-- inputs -->
<button type="button">action 1</button>
<button type="button">action 2</button>

<button type="submit">Submit form</button> <!-- With "Enter" this one will be triggered-->
EliuX
  • 11,389
  • 6
  • 45
  • 40
0

I also want to add, that if you have nested <form>'s, then only <input> directly in form will fire submit on enter, input's in nested forms does not work.

<form submit="onSubmit">
 <input type="text" name="submits-on-enter" />
 <form submit="onSubmitNested">
    <input type="text" name="DOES-NOT-submit-on-enter" />
 </form>
 <button type="submit">SAVE</button>
</form>
Luckylooke
  • 4,061
  • 4
  • 36
  • 49
0

Also, make sure there is one and only one submit button in the form.
i.e. a single

<input type="submit">

statement

This is applicable even if you are hiding or showing it using JavaScript.

If for some reason you have multiple submit buttons in your form, the only available approach is to listen to submit events using JavaScript.

Mohit Kanwar
  • 2,962
  • 7
  • 39
  • 59
0

There's another reason that's not mentioned in the other answers.

In Google Chrome (but not iOS Safari, etc.) it triggers the click event on buttons and inputs that have type="submit", and if any handler on that event calls preventDefault() (or return false; in jQuery) then it actually cancels the form submit!!

So when you press <Return> while focused in an input element, that's inside a form that has a such a button, please go to the developer console and check out all the Event Listeners. Remove them one by one, and try to press <Return>. If this fixes the issue, you know which event handler messed it up for you.

Took me an hour of debugging to realize this!!

Gregory Magarshak
  • 1,883
  • 2
  • 25
  • 35