You are here: Home » All Posts » Javascript Form Handling » How to use getElementById to get the elements in a form

How to use getElementById to get the elements in a form

in Javascript Form Handling

Sample code
Download the sample code here: getelementbyid-form-sample.zip

There are many ways of accessing form elements, of which the easiest is by using the cross-browser W3C DOM document.getElementById() method. Before we learn more about this method, it would be useful to know something about the Document Object Model (DOM), the concept of HTML nodes or elements, and the concept of containers.

Each time you load an HTML page, the web browser generates an internal representation of the page in the form of an inverted tree structure. Let us look at a simple form. We will use this form later to demonstrate the use of the getElementById method.

<form name ="subscribe" id="subscribe_frm" action="#">

Your Name: <input type="text" name="name" id="txt_name" />

Your Email: <input type="text" name="email" id="txt_email" />

<input type="button" name="submit" value="Submit"
onclick="processFormData();" />

</form>

There are elements such as <input/> and containers like <form> </form> Each element can have attributes associated with it, such as:

<input type="text" name="name" id="txt_name">

Here, the <input/> element has three attributes: type, name and id. The id attribute uniquely identifies this particular element.

Accessing Form Elements using getElementById

In order to access the form element, we can use the method getElementById() like this:

var name_element = document.getElementById('txt_name'); 

The getElementById() call returns the input element object with ID ‘txt_name’ . Once we have the object, we can get the properties and call the methods of the object. For example, to get the value of the input element, get the value attribute.

var name = name_element.value;

Similarly, it is possible to access the <form> element:

var frm_element = document.getElementById ('subscribe_frm');

Example: access the form and input elements

See the demo.
In this demo, we toggle the visibility of the form. This is done by accessing the form element <form> which we have seen above and setting its display property as shown in the code below:

var frm_element = document.getElementById('subscribe_frm');

var vis = frm_element.style;

if (vis.display=='' || vis.display=='none')
{
    vis.display = 'block';
}
else
{
    vis.display = 'none';
}

Example: Input validation

The code below makes sure that the field is not empty.
First, we trim out any leading and trailing blank space.

function trim (str)
{
     return str.replace (/^\s+|\s+$/g, '');
}

The code below validates the txt_name field.

var name_element = document.getElementById (‘txt_name’);

if (trim(name_element.value) == '')
{
   alert ('Please enter your name');
}

Checking for getElementById support

All modern browsers support getElementById() method. However if you are to support very old browsers, use the following function:

function getElement (id)
{
   if (document.getElementById)
   {
      return document.getElementById(id);
   }
   else if (document.all)
   {
      return window.document.all[id];
   }
   else if (document.layers)
   {
      return window.document.layers[id];
   }
}

Other Cross-browser ways of accessing form element objects

There are two other cross-browser ways of accessing form elements: document.getElementsByTagName and document.getElementsByName.

Using the document.getElementsByTagName Method

This method takes in as argument the name of a tag (element) and returns an array of all matching tags (elements) found in the document.

In our form example, if we had to get a reference to all the <input> elements, we could use the following code:

var inputs = document.getElementsByTagName('input');

The variable inputs is a reference to an array of all <input> elements including: <input type=”button”>

getelementbyid example 2

What if we only wanted to access <input> elements with the type attribute as text? We could do it in the following way:

var inputs = document.getElementsByTagName("input");
var message =
   "The form has the following input elements with the 'type' attribute = 'text': \n\n";

for (var i=0; i < inputs.length; i++)
{

   if (inputs[i].getAttribute('type') == 'text')
   {
      message += inputs[i].tagName +
      " element with the 'name' attribute = '";
      message += inputs[i].getAttribute('name') + "'\n";
   }
}
alert(message);

This time, the elements retrieved do not include the element: <input type=”button”>.

getelementbyid example 3

Using the document.getElementsByName Method

This method takes in as argument the name attribute value of elements to be retrieved and returns a collection of desired matching elements.

In the code snippet below, let us say we need to get a reference to the <select> element with the name attribute mail_format.

<select name="mail_format" id="slt_mail_format">
<option value="TEXT">Plain Text</option>
<option value="HTML">HTML</option>
</select>

We could access the desired element in this way:

var mail_format_elements = document.getElementsByName('mail_format');

getelementbyid example 4.

Be Sociable, Share!
Reach out:

Prasanth Janardanan

Prasanth is the founder of Simfatic Solutions. He loves exploring Javascript possibilities and shares some great tips and some code here at Javascript-Coder.com.
Most of the time, Prasanth is busy adding features to Simfatic Forms - a desktop based Web Form Builder.
Reach out:

Latest posts by Prasanth Janardanan (see all)

{ 21 comments… read them below or add one }

Guest November 8, 2013 at 6:22 am

thanku

Reply

Nguyễn Hữu Thiên Sơn August 3, 2013 at 1:56 am

hello. I’m from Vietnam SON. I have one problem when interacting with Web applications. Can you help me?

When interacting with the site: http://tny.cz/. I’m having problems with the submit button.

Reply

alex July 19, 2013 at 12:32 pm

ive been using jQuery since last year but it is my first time in javascript. thanks a lot for these articles.

Reply

Jan Daryl F. Fabregas February 23, 2013 at 3:10 pm

you help me a lot.. for that I will follow you. :))))

Reply

Alon May 17, 2012 at 12:49 pm

Very useful thanks for the great articles !

Reply

Andy May 14, 2012 at 1:34 pm

Hi

I found this comment very useful.

Reply

mani December 30, 2011 at 11:05 am

which one i
set in place of src=openlayers.js

Reply

Natan Prompra December 5, 2011 at 10:10 am

Script very useful. It helps me a lot understanding DOM in HTML. Thanks.

Reply

Celestino Veiga December 2, 2011 at 6:48 pm

I’m beginner on javascript language. This post is very usefull for understand the DOM and how to access each element/value of the DOM.

Reply

Nikhil October 25, 2011 at 6:53 am

how to call document.getElementsByName Method if name contains spaces like “Sign In”

Reply

Justin October 20, 2011 at 2:43 pm

Well said. Clear and concise.

Reply

pankaj September 16, 2011 at 9:11 am

Hey this script was really useful. Thanks.

Reply

Shubham August 16, 2011 at 9:31 am

Please tell me how to check for the value of checkbox using this . it will be helpful!!
Thanks in advance

Reply

Lance August 14, 2011 at 1:59 pm

Cool! I am a beginner, is there anywhere (website/book/tutorials) where I can get more of such??

Please help me
Thank you verymuch.

Reply

prasanth August 16, 2011 at 3:40 am
francesco July 29, 2011 at 5:42 pm

Hi i have a question.
I have a JavaScript code that block my script with IE 7 an 8, the error is:

“Proprieties or method not supported”

and the cause is this snippet of code:
email = document.getElementById(“email”).value;

Do you know how to fix this problem?
Thanks a lot.
Francesco

Reply

James K December 8, 2011 at 8:36 pm

In the example, there is no field with the id set to “email”. I think it may work if you change your code to:
email = document.getElementByName(‘email’).value;

Reply

Mito July 4, 2011 at 10:08 pm

je suis content

Reply

jacks June 20, 2011 at 12:34 pm

Hey this script was really useful. Thanks.

Reply

TrialBuyFire February 18, 2011 at 8:15 pm

Nice post.  Very clear and concise with easy to understand examples.  Also really like the layout and use of color…

Reply

Ratan Mohapatra January 20, 2011 at 3:19 pm

Perfect refreshment! Keep it up.

Reply

Leave a Comment

Previous post:

Next post: