Web Development optimize

Accessing form data via JavaScript and the DOM

The HTML Document Object Model (DOM) provides everything necessary to access the contents of an HTML page. Tony Patton examines the various ways to access page elements and describes how to create them.

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). 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.

Weekly development tips in your inbox
Keep your developer skills sharp by signing up for TechRepublic's free Web Development Zone newsletter, delivered each Tuesday.
Automatically sign up today!

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).

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 utilize the getElementsByTagName method as opposed to the other methods. I simply check each element of the array for values to perform validation.

The two examples utilize 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.

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.

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

  1. I begin with the top of the page, so I can start with the document object.
  2. The first element within the body of the page and the document object is the form.
  3. 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.

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.

Miss a column?

Check out the Web Development Zone archive, and catch up on the most recent editions of Tony Patton's column.

About

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

9 comments
nanookj
nanookj

The Listing links (A, B, C) go to broken pages.

rfoth
rfoth

IE is broken in that it allows indices to use parentheses (). Changing it to brackets lets this work in standard compliant browsers - so change the onclick event to this - onclick="document.getElementsByTagName('p')[0].innerHTML = document.getElementById('fullNameField').value;"

tlw0799
tlw0799

In Listing A, where you test for fullname not null and value equal to spaces, should the else cause flag to be set to true rather than false? Same question for contactnumber.

Len Harding
Len Harding

I just changed the line that sets the variable to use brackets. So now you have: var contactnumber = document.getElementsByName("contactNumber")[0]; Code runs fine in Firefox and IE after that.

leeharvey1
leeharvey1

Yes. In addition to these basic syntax errors... varfullname = varcontactnumber = ...which should be: var fullname = var contactnumber =

Len Harding
Len Harding

Your code change was for example C while I was still on A.

MaryWeilage
MaryWeilage

Thanks for making us aware of the issues with the listings. I contacted the author, and we have updated Listings A and B. Thanks again, Mary Weilage Newsletter Editor