JavaScript Page 6 - Understanding The JavaScript Event Model (part 1) |
JavaScript also includes a bunch of event handlers for forms and form elements, including text fields, selection lists, and buttons. The onSubmit handler is triggered when a form is submitted. This handler is usually placed in the <form> tag. For example, consider the following form, which asks the user to enter a value into the text field and then pops up an alert with a message incorporating that value: Of course, this isn't all that useful. Here's another, more practical example:
In case you haven't figured this one out yet, it pops up a warning dialog box if the user attempts to submit the form with an invalid name or email address - very useful when you want to cut down on mistyped or incorrect data being entered into your forms.There's one important quirk of the onSubmit handler that you should know about, because I've used it in both scripts above. Once the onSubmit event handler is invoked, the browser decides whether or not to process the form further on the basis of the value returned by the event handler. If the handler returns false, the form is not processed further; if it returns true, the form is submitted to the named form processing script. As the example above demonstrates, this comes in particularly handy when attempting to perform JavaScript-based validation of form data. It's possible to write a comprehensive set of JavaScript routines to verify the data entered into the form by the user, activate these routines via the onSubmit handler once the user submits the form, and only process the data in the form if the validation routines return a positive result. This is a technique used commonly on the Web to reduce the incidence of bad data entry.
blog comments powered by Disqus |