5

I have a form for logging into my website. I need to make it so that when the user hits enter, the form submits. How can I do this? Please provide code. Thanks.

          <form id="login" action="myHome.php" method="POST">
            <input type="text" name="email" id="email"/>
            <br/>
            <br/>
            <input type="text" name="password" id="password"/>
          </form>
9

Have you actually tried anything?

You need to add an <input type="submit"> and hide it with CSS so that the browser knows what to trigger when enter is pressed, yet still not show a button. For the sake of accessibility and ease of use, I'd show the button even if not that many people use it (enter is much nicer).

2
  • For me this only worked when the cursor was in one of the text fields, not if tabbing to the hidden submit button. The jQuery solution worked for me.
    – Gruber
    Oct 18 '13 at 10:33
  • You can also do <button type="submit">Submit</button>, if you're targeting HTML5 compliant browsers.
    – BBaysinger
    Feb 20 '18 at 1:34
6

add a handler to on keydown and check for keycode == 13. Make this submit the form like below

function addInputSubmitEvent(form, input) {
    input.onkeydown = function(e) {
        e = e || window.event;
        if (e.keyCode == 13) {
            form.submit();
            return false;
        }
    };
}
1
  • would it be better for it to be handled naturally by the form submission mechanism instead of short-circuiting it by using the keycode 13 detection to do the trick? Feb 5 '20 at 7:26
0

This should happen by default. In my experience some browsers require an <input type=submit> field, but generally this is not a requirement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.