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

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) {
        $('#password').focus();
        event.preventDefault();
    }
});

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.


I was looking for a solution to this problem and want to share my solution, based on many posts over here. (Tested on modern Chrome/Firefox/IE)

So, using only Javascript the follow code submits the form if ENTER key is pressed on any field or if the button Submit is pressed. After that it clear/reset the form, which is a nice thing to do.

Hope it helps.

<!DOCTYPE html>
<html>
<body>
<p>Based on http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_ev_onsubmit</p>
<p>When you submit the form, a function is triggered which alerts some text.</p>

<div onKeyPress="return myFunction(event)">
  <form id="form01" action="demo_form.asp" onsubmit="return false;" >
    Enter name: <input type="text" name="fname">
    <input type="button" value="Submit" onclick="myFunction(0)">
  </form>
</div>

<script>
function myFunction(e) {
   if((e && e.keyCode == 13) || e == 0) {
     alert("The form was submitted");
     document.forms.form01.submit();
     document.forms.form01.fname.value = ""; // could be form01.reset as well
   }
}
</script>

</body>
</html>