May 1, 2000 - Form Cancellation | WebReference

May 1, 2000 - Form Cancellation

Yehuda Shiran May 1, 2000
Form Cancellation
Tips: May 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

A form can be submitted via the Enter key when it consists of only one text field, and the cursor is currently located in that field. Sometimes, we want to force an action by the Enter key, without submitting the form. The trick is to use the onSubmit event handler, do the required action when the trigger goes off, and then cancel the event by returning a false value. In this way, we still utilize the advantages of the submit button (submission via the Enter key) without actually submitting the form.

Let's take an example. Suppose a form's header is defined as:

<FORM NAME="organizer", onSubmit="display(); return false;">

and is composed of two elements:

  • A submit button,
  • VALUE="Display"

    The user can submit the form by clicking the button labeled "Display," or by pressing Enter when the cursor is located in the text field. When the user submits the form, the onSubmit event handler is triggered. It invokes the display() function.

    The onSubmit event handler returns false in order to cancel the form's submission. If we aren't really submitting the form, then why didn't we use a standard button instead of a submit button? The answer is simple. If we used a standard button to invoke display() via its onClick event handler, that would be the only way to call display(). By using the form's onSubmit event handler to call the function, the user can also load the desired page by pressing Enter within the text field.

    Learn more about canceling a form submission in Column 15, Lookup Lists.