Section 7.1. Accessing the Form


7.1. Accessing the Form

In JavaScript, forms are accessed through the DOM via the document object using a couple of different approaches. The first is to access the form using the forms property on document. Forms are just one of the many page elements collected in arrays. If the page only has one form, access it at the array index zero (0):

var theForm = document.forms[0];

The forms are added to the collection in the order in which they appear in the web page. As you can imagine, if you modify the page, you may end up knocking your JavaScript out of whack. A better approach would be to name the form and access it from the document object by name:

<form name="someform" ...> ... var theForm = document.someform;

As discussed in earlier chapters, there are also a couple of ways to intercept a form before submitting it to the server. The event you're going for is submit on the form. However, you can trap the submit event using an inline event handler, a traditional handler, or the addEventListener/attachEvent option. The key is that once you've validated the form contents, you need to be able to cancel the event if the contents fail. In the next section, we'll look at how to attach an event handler and cancel a form submittal, based on the different event-handling approaches.




Learning JavaScript
Learning JavaScript, 2nd Edition
ISBN: 0596521871
EAN: 2147483647
Year: 2006
Pages: 151

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net