By default in most browsers, hitting the Enter key will trigger the browser to follow the the URL or button that currently has tab focus. Sometimes it seems as though the browser does whatever it wants after the user hits Enter because the focus isn’t readily apparent. In an interface with one or more forms, it is preferable to have the Enter key trigger the submission of the form so that the user isn’t forced to use his pointer to click the submit button. It’s also nice to include this feature to avoid data loss when the user inevitably hits Enter and the browser decides to go wherever it feels like it.
In this example, we add code that allows the user to submit a form with the enter key using jQuery.
<div id='form_1'> Field 1: <input type='text' name='field_1' id='field_1'> <p> </p> <button type='button' id='form_1_submit_button'>Submit</button> </div>
In the following jQuery code, we have a self-executing anonymous function that binds a click event handler to #form_1_submit_button and an event handler for the Enter keypress inside #form_1. Whether the user specifically clicks the submit button or hits the Enter key anywhere inside the form, the ValidateForm() function is called.