Understanding HTML Forms with JavaScript


document.forms[0] 

Usually, you access an HTML element using its ID and then document.getElementById(). However, with HTML forms, document.forms is generally used.

One reason for this is that the name attribute of each form element is used when the form is submitted to the server.

document.forms is an array of all forms on the current page. So if the form contains only one form, document.forms[0] accesses it. Alternatively, forms can also get a name:

<form name="mainForm"> ... </form> 


Then, document.forms["mainForm"] accesses the form.

All elements within the form are also referenced by their name, serving as array index for the elements property of the form. For instance, imagine that the first form on a page has an element with the attribute name="element1". Then, the following JavaScript code accesses this element:

document.forms[0].elements["element1"] 


There are also shorter versions to access form information. A form named "mainForm" and an element "element1" allows this shortcut:

document.mainForm.element1 


Generally, the more detailed approach using the forms array and especially the elements array is used, since this can also be used with automated access to the form elements.

JavaScript can modify form elements, act upon certain events being triggered, and also submit the form (and prevent it from being submitted). Also, JavaScript can come in handy with regard to form data validation. Do, however, always keep in mind that JavaScript can be deactivated. The form must also work without JavaScript.

Tip

Every form element supports the form property, which points to the form the element resides in. Therefore, this.form is used quite often in the code for form field elements to grant easy access to the element's form, without having to go through the document.forms array.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

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