Often as a User we don’t want to use our mouse or tab to the submit button to submit a form on a Web page, instead we may just want to press the enter key on our keyboard. This functionality can be easily completed by performing a bit of JavaScript, personally I find that utilizing JQuery makes the task even easier.

Enabling Enter Button to Submit a Form

To enable the enter button for a form we will create a javascript function that check when a key is pressed when an input element of the form is in focus. This function can then either submit the form or call another javascript function to validate the form.

  1. First lets we will start by defining our start-up function that will setup the appropriate keydown handlers on the input fields.
    $(document).ready( function() {
        // code from step 2
    }
  2. Second we will need to set the keydown handler for all input fields in our form including select and radio fields. JQuery provides a shortcut selector :input to select these elements.
    $('#formID :input').keydown(function(e) {
        // code from step 3
    }
  3. Now time to fill out the logic of the function called when the enter key is pressed. First we will want to verify that we have the event to do this we can check if e is null and get the window.event instead. To shorten this we can simply use the || operator.
    var event = e || window.event;

    Next we check if the key pressed was the enter button by use of the keyCode property.

    if( e.keyCode == 13) {
        // action here
    }
  4. The last step is simply put in the action logic whether it is calling a validation script:
    return validateForm();

    or submitting the form directly

    document.formName.submit();

Full Sample Script

$(document).ready( function() {
    $('#myForm :input').keydown(function(e) {
        var event = e || window.event;
        if (e.keyCode == 13) {
           return validateForm();
        }
    });
});

Resources

,

The standard approach to submit a form is through the use of the submit button. However we may find that we may want to utilize an image, text link or other elements to submit a form. In these cases we can utilize JavaScript to submit the form for us through the use of the JavaScript form object.

When your html page contains a form then a form object is created in your document that can be accessed by its name.  The form object contains both the submit and reset functions. To access the form object we use the notation document.FORM_NAME.

Examples

HTML Form

<form name='mailForm' method="POST">
   // form contents
</form>

JavaScript Form Submit

<a href="javascript: document.mailForm.submit()">Send mail</a>

JavaScript Form Reset

<a href="javascript:  document.mailForm.reset()">Clear</a>

Javascript Method

<SCRIPT language="JavaScript">
  function sendEmail ()
  {
     document.mailForm.submit();
  }
</SCRIPT>
 
<a href="javascript: sendEmail()">Send mail</a>
, ,