charliebrownie charliebrownie - 6 months ago 25
HTML Question

HTML5: How to make a form submit, after pressing ENTER at any of the text inputs?

The title speaks for itself... I have a couple of forms, one of them is just a single text input form and the other one is composed by two text inputs. I do not want any submit button in any of them, I want each form to submit whenever the user presses the ENTER button at any text input:

  1. The form composed by just one input submits everytime the user presses the ENTER button - Perfect!

  2. The second form composed by two text inputs does not behave this way, it does not submit when the user presses the ENTER button at any of both inputs.

Is there a way to make a form with more than one text input behave this way and avoid having a submit button in it?


Try adding this between the <form></form> tags

<input type="submit" style="display: none" />

Tested it and it works on Firefox and Chrome. If you have a submit input type in the form, enter should automatically submit it, regardless of whether it's visible or not.

I am actually using this myself in a login form, though in the username field, it makes more sense to move to the next field than to submit. Just in case you have a similar use case, here's the code I used (requires jQuery)

$('#username').keypress(function(event) {
    if (event.keyCode == 13 || event.which == 13) {

Note that there is a slight bug though -- if the user selects a browser autocomplete username and presses enter, it still moves to the next field instead of selecting it. Didn't have time to debug this, but if someone can figure out how to fix it, that would be cool.