Accessing Form Data via JavaScript and the DOM

From PeformIQ Upgrade
Jump to navigation Jump to search

Tony Patton, TechRepublic

Accessing and manipulating the various elements on a Web page is a common endeavor that is easily accomplished with JavaScript and the HTML Document Object Model (DOM) (http://www.w3.org/DOM/). In this article, I examine the various ways to access page elements and describe how to create them.

The HTML DOM

To quote the W3C, "The Document Object Model is a platform- and language-neutral interface that will allow programs and scripts to dynamically access and update the content, structure and style of documents."

All HTML elements, along with their containing text and attributes, can be accessed through the DOM. An element's contents can be modified or deleted as well as the creation of new elements.

When working with the DOM and page elements, the most important object is document. It is contained within the windows object, but you can just type document in JavaScript code and use it. It represents the entire HTML document while providing access to all of the elements in a page. You may access page elements via collections, properties, and methods. For this article, I will focus on accessing fields on a Web page using various approaches.

Accessing data

As you work with a page and its data, you will often need to gain access to an element and massage the data associated with it. The following methods are available via the DOM and JavaScript to access individual page elements.

* getElementById(): Returns a reference to the first object with the specified id passed to the method.
* getElementsByName(): Returns a collection of objects with the specified name passed to the method.
* getElementsByTagName(): Returns a collection of objects with the specified tag name passed to the method.

Listing A contains a simple example that uses the first two methods in the previous list. It includes a form with two fields, and the data must be entered in the two fields before the document may be submitted. The getElementById method is used to access the first field with the correct id (i.e., the value assigned to the input field via its ID attribute) passed to it. The getElementsByName method is used to access the second field via the value assigned to its name attribute. The getElementsByName method returns an array of values, so I am only concerned with the first value (i.e., the zero array index value).

Listing A

 <html><head>
 <title>Accessing elements via DOM</title>
 <script type="text/javascript"> 
 function validate(){var flag = true;var fullname =
 document.getElementById("fullNameField");var contactnumber =
 document.getElementsByName("contactNumber")(0);
 if (fullname != null) {
 if (fullname.value == '')     {
 flag = false;
 } 
 } else {
 flag = true;
 }
 if (contactnumber) {
 if (contactnumber.value == '') {
 flag = false;
 }
 } else {
 flag = true;
 }
 if (flag) {
 alert('Validation successful, document will be
 submitted.');document.submit();
 } else {
 alert('Enter values before submitting.');
 }
 return 0; }
 </script></head><body>
 <form id="frmDOMExample">
 Name: <input name="fullName" id="fullNameField" type="text"><br>
 Number: <input name="contactNumber" id="contactNumberField"
 type="text"><br>
 <input id="submitButton" type="button" value="Submit"
 onclick="validate();">
 </form></body></html> 

I could opt for a different approach for this situation by using the getElementsByTagName method. This allows you to populate an array object with all of the elements within a page with a specific tag name. For example, the following line assembles an array of all table cell (td) elements on the page:

var columns = document.getElementsByTagName("td");

For my example, I am interested in the input fields on the form. Listing B alters the previous example to utilise the getElementsByTagName method as opposed to the other methods. I simply check each element of the array for values to perform validation.

Listing B

 <html><head>
 <title>DOM Test - getElementsByTagName</title>
 <script type="text/javascript"> 
 function validate() {
 var flag = true;
 var fields = document.getElementsByTagName("input");
 if (fields(0) != null) {
 if (fields(0).value == '') {
 flag = false;
 } } else {
 flag = true;
 }
 if (fields(1)     ) {
 if (fields(1).value == '')    {
 flag = false;
 } } else {
 flag = true;
 }
 if (flag) {
 alert('Validation successful, document will be
 submitted.');document.submit();
 } else {
 alert('Enter values before submitting.');
 }
 return 0;
 }
 </script></head><body>
 <form id="frmTest">
 Name: <input name="fullName" id="fullNameField" type="text"><br>
 Address: <input name="contactNumber" id="contactNumberField"
 type="text"><br>
 <input id="submitButton" type="button" value="Submit"
 onclick="validate();">
 </form></body></html>

The two examples utilise input fields, so I don't want to imply they are the only elements that may be accessed via the document object and its methods. Listing C takes data entered into one of the input fields and places it in a paragraph element. The paragraph element is populated once the user selects the Submit button.

Listing C

 <title>DOM Example</title>
 </head><body>
 <form id="frmDOMTest">
 Name: <input name="fullName" id="fullNameField" type="text"><br>
 Number: <input name="contactNumber" id="contactNumberField"
 type="text"><br>
 <input id="submitButton" type="button" value="Submit" </form>
 <p>Hey there.</p>
 </body></html>

Another approach

I don't want to leave out probably the most common way to access elements, especially form data, contained by a Web page. This approach walks the DOM tree to locate an element and access or manipulate it and/or its contents. A visual diagram of a Web page provides an excellent visual source, but a quick glance at the source of a page provides ample information. For example, let's say I need to access the input field called txtAddress in the page in Listing D.

Listing D

 <title>DOM Tree</title>
 </head>
 <body>
 <form id="frmTest">
 Name: <input name="fullName" id="fullNameField" type="text"><br>
 Address: <input name="address" id="addressField" type="text"><br>
 <input id="submitButton" type="button" value="Submit">
 </form>
 </body>
 </html>

I can walk the DOM for the HTML to get to the element I need by following these steps:

# I begin with the top of the page, so I can start with the document object.
# The first element within the body of the page and the document object is the form.
# Once in the form element, I stumble upon the address field.

At this point, I stop since I found the desired element. So, I start with the document object, proceed to the form, and end with the input element named address. HTML forms are contained in forms property of the document object. It returns an array of the forms on the page, so I can access the form with its index value (which is 0 since it is the first). You can also access the form using its name as a property of the document object. The following example accesses the address element and its value using the first approach:

 document.forms[0].address.value;

Or, you could use the actual form name (as specified in the form element's name attribute) as noted here:

 document.frmTest.address.value;

In Listing E, I rework the first example to use this approach to access page elements and values for the purpose of validation.

Listing E

 <title>Accessing elements via DOM</title>
 <script type="text/javascript"> 
 function validate() {
 var flag = true;
 varfullname = document.frmTest.fullName;
 varcontactnumber = document.forms[0].contactNumber;
 if (fullname != null) {
 if (fullname.value == '')     {
 flag = false;
 } } else {
 flag = false;
 }
 if (contactnumber) {
 if (contactnumber.value == '') {
 flag = false;
 } } else {
 flag = false;
 }
 if (flag) {
 alert('Validation successful, document will be submitted.');
 document.submit();
 } else {
 alert('Enter values before submitting.');
 }
 return 0; }
 </script></head><body>
 <form id="frmTest" name="frmTest">
 Name: <input name="fullName" id="fullNameField" type="text"><br>
 Number: <input name="contactNumber" id="contactNumberField"
 type="text"><br>
 <input id="submitButton" type="button" value="Submit"
 onclick="validate();">
 </form>
 </body>
 </html>


Get what you need

The DOM provides everything necessary to access the contents of an HTML page. It allows you to access and manipulate data it contains as well as much more.

The concepts presented in this column may seem simple to veteran Web developers, but those new to the field need to be aware of the many ways to accomplish a task.

Offer tips about using the DOM with the Web development community by posting to the article discussion.