Form Basics


Traditionally, JavaScript provides access to the forms within an (X)HTML document through the Form object (known as an HTMLFormElement in the DOM), which is a child of the Document object. As with all document objects, the properties and methods of this object correspond to the various features and attributes of the (X)HTML << form >>, which is summarized here:

 <<form  id="Unique alphanumeric identifier"  name="Unique alphanumeric identifier (superseded by id attribute)"  action="URL to which form data will be submitted "  enctype="Encoding type for form data"  method="Method by which to submit form data (either GET or POST)"  target="Name of frame in which result of submission will appear">>  Form field elements and other markup giving form structure  <</form>> 

As we have seen already in our discussion of object models, most of the JavaScript properties for the Form object should correspond to the attributes of the << form >> tag. A summary of the most useful properties available from JavaScript s Form object is presented in Table 14-1.

Table 14-1: Major Properties of the Form Object

Property

Description

action

Holds the value of the action attribute indicating the URL to send the form data to when the user submits.

elements[]

Array of form fields objects representing the form field elements enclosed by this < form >.

encoding

Holds the value of the enctype attribute, which usually contains the value application/x-www-form-urlencoded , multipart/form-data or text/plain . Superseded by the enctype property.

enctype

The DOM-appropriate way to access the enctype attribute value.

length

The number of form fields within this < form > tag. Should be the same as elements.length .

method

The value of the method attribute of this < form > tag. Should be either GET or POST .

name

The name of the < form > as defined by its name attribute.
You probably should also set the id attribute to hold the
same value.

target

The name of the frame in which to display the page resulting from form submission. May hold special frame values, such as a _blank , _parent , _self , or _top .

Form s also have two form-specific methods. The reset() method clears the form s fields, similar to clicking a button defined by << input type="reset" / >>. The submit() method triggers the submission of the form similar to clicking the button defined by << input type="submit" / >>. In addition to the ability to trigger form reset and submission, you often want to react to these events as well, so the << form >> tag supports the corresponding onreset and onsubmit event handler attributes. As with all events, handler scripts can return a value of false to cancel the reset or submit. Returning true (or not returning a value) permits the event to occur normally. Given this behavior, the following form would allow all form resets but deny submissions:

 <<form action="sendit.cgi" method="get" onreset="return true;"  onsubmit="return false;">> ...  form fields here  ...  <</form>> 
Note  

A troublesome aspect of calling the submit() method is that it typically bypasses any onsubmit event handler. The reasoning is that since you re triggering submission with script, your script should also be capable of doing whatever the event handler does.

Accessing Forms

Before exploring examination and manipulation of form fields, we need to make sure that we are capable of accessing a Form properly. Forms can be accessed in at least three ways: by number through document.forms[] , by name through document.forms[] , or by the regular element retrieval mechanisms (e.g., document. formname or, in DOM-supporting browsers, document.getElementById() ). For example, to access the form in an HTML document defined here,

 <<form name="customerform" id="customerform" action="#" method="get">> <<input type="text" name="firstname=" id="firstname=" />><<br />> <<input type="text" name="lastname=" id="lastname=" />>      ...more  fields... <</form>> 

we might use window.document.forms[0] ( assuming it s the first form in the page), window.document.forms['customerform'] , or window.document.customerform , just as with any other JavaScript collection.

Accessing a form by name is far preferable to accessing it by its index in the forms[] collection since the ordering of << form >> tags in the document could change.

Accessing Form Fields

Just as the Document contains a collection of << form >> tags, each form contains a collection of form fields that can be accessed through the elements[] collection. So, given the form of the previous example, window.document.customerform.elements[0] refers to the first field. Similarly, we could access the fields by name, for example, with window.document .customerform.firstname or window.document.customerform.elements["firstname"] .

We could also iterate through the collection of form fields after examining the elements[] collection s length property ( window.document. customerform.elements .length ). Conveniently, the length of the elements[] collection is also stored in the Form . This gives us a shorthand notation for looking at the number of fields: document .customerform.length .

Before taking a look at the objects that represent the different kinds of form fields, we present a brief example to demonstrate the access of the various Form object properties and methods.

 <<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">> <<html>> <<head>> <<title>>Form Object Test<</title>> <<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />> <</head>> <<body>> <<h2 align="center">>Test Form<</h2>> <<form action="http://www.javascriptref.com/formEcho"      method="post" name="testform" id="testform"       onreset="return confirm('Are you sure?');"      onsubmit="alert('Not really sending data'); return false;">> <<label>>Name:  <<input type="text" id="field1" name="field1" size="20"        value="Joe Smith" />><</label>> <<br />> <<label>>Password:  <<input type="password" id="field2" name="field2"         size="8" maxlength="8" />><</label>> <<br />> <<input type="reset" value="reset"/>> <<input type="submit" value="submit" />> <<input type="button" value="Do reset"         onclick="document.testform.reset();" />> <<input type="button" value="Do submit"         onclick="document.testform.submit();" />>  <</form>> <<hr />> <<h2 align="center">>Form Object Properties<</h2>> <<script type="text/javascript">> <<!-- // Change document.testform to document.forms[0] and you will // get the same result. with (document.testform) {    document.write("action: "+action+"<<br />>");    document.write("encoding: "+encoding+"<<br />>");    document.write("length: "+length+"<<br />>");    document.write("method: "+method+"<<br />>");    document.write("name: "+name+"<<br />>");    document.write("action: "+action+"<<br />>");    document.write("target: "+target+"<<br />>");    for (var i=0; i<<document.testform.length; i++)         document.write("element["+i+"].type="+                        document.testform.elements[i].type+"<<br />>"); }      //-->> <</script>> <</body>> <</html>> 

A rendering of this example is shown in Figure 14-1.

click to expand
Figure 14-1: Exercising basic Form methods and properties



JavaScript 2.0
JavaScript: The Complete Reference, Second Edition
ISBN: 0072253576
EAN: 2147483647
Year: 2004
Pages: 209

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