You are here: Home » All Posts » Javascript Form Handling » Using JavaScript to access form objects when there are multiple forms

Using JavaScript to access form objects when there are multiple forms

in Javascript Form Handling

In order to access a form through JavaScript, we need to obtain a reference to the form object. One obvious way to approach, is to use the getElementById method. For instance, if we had a form with the id attribute "subscribe_frm", we could access the form in this way:

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

However, this approach has the limitation that the <form> tag must have an id attribute, as the getElementById method needs the id of an element in order to locate it in the DOM tree. Fortunately, JavaScript provides us with alternatives where you can get the form when you don’t have the id attribute.

One way to approach is to make use of the this keyword which always points to the object that is calling a particular method. Used in conjunction with the onClick event handler of a form’s submit button, we can get a reference to the form itself, through the this.form property, even if there are multiple forms on the page.

The other alternative is to use the document object’s forms collection to obtain a reference to the form object. The forms collection is a JavaScript array that holds references to all the forms present in a web page. We can access each form reference either by it’s index in this array or by it’s name attribute. Let us look at each of these methods of accessing multiple forms in details.

Accessing the form object through JavaScript using the this.form property

Every element in a form triggers events based on user action which can be handled by an appropriate event handler. For instance, the submit button on being clicked triggers the onClick event handler. Since the 'this' keyword in JavaScript always points to the object that calls a given method, the onClick event handler can be passed ‘this’ self reference to obtain a reference to the button element object.

Moreover, in JavaScript, every element object of a form has a property that references the form object. So, if we were to pass this.form to the onClick event handler of a form button, this function would get the reference to the form object. This is an easy way to access form objects, even if there are multiple forms on a web page, because the form’s name or id attribute are never directly used. Let us have a look at an example.

<form name ="submit_bookmark" action="#">

Page Title: <input type="text" name="page_title" size="50">

Page URL: </label><input type="text" name="page_url" size="50">

Tags (comma separated): <input type="text" name="tags_list" size="40">

<input type="button" name="submit" value="Save Bookmark" onclick="showElements(this.form);">

</form>
 

In the form above, the showElements onClick event handler of the form button is being passed this.form. Here this refers to the button object, and this.form references the form object. We could now use this form object in the showElements function and access the form and all it’s elements.

Have a look at this demo which shows two form on a web page. You can also download the code.

Accessing multiple Forms using the document object’s forms collection

The document object of a web page has a property named forms which is a JavaScript array that holds references to all the form objects on the page. We can get a reference to individual forms by using the index of the forms or by using their names. Please note that this array’s index begins at 0.

For instance, if we have two forms “submit_article” and “submit_bookmark” appearing on a web page in this order, we can access the form named “submit_bookmark” in the following two ways:

var oForm = document.forms[1]; 

OR

var oForm = document.forms["submit_bookmark"]; 

We can use the same approach to access individual form elements as well. Every form field of a form is contained in the form’s elements collection which is a JavaScript array similar to the document object’s forms collection.

To access the text input field named “tags_list” of the form named “submit_bookmark” (which was the second form on the web page, as you saw in the demo), we can use one of the following methods:

  • First, get the form reference:
  • var oForm = document.forms["submit_bookmark"];
  • Next, we get the reference to the “tags_list” element in one of the following ways:
  • var oTagsList = oForm.elements[2]; OR
    var oTagsList = oForm.elements["tags_list"];
    
  • To get the value of the input element, as before:
  • var tags = oTagsList.value; 

Please have a look at this detailed demo to understand the concepts presented.
Download the code.

Example: Copy from one form to other

Let us say that we had to copy the value of an element in one form into an element in another form. Have a look at this demo.

We could implement this by passing the names of the two forms as well as the names of the source and target elements to a javascript function:

<a href="#" onClick=" javascript: copyFormElementToElementOfDifferentForm('submit_article', 'submit_bookmark', 'site_cat', 'tags_list');">Copy site_cat element value of the first form to the input field named "tags_list" of the second form</a>
 

Have a look at the implementation of this function:

var oForm1 = document.forms[oForm1Name];
var oForm2 = document.forms[oForm2Name];
var oForm1Element = oForm1[oForm1ElementName];
var oForm2Element = oForm2[oForm2ElementName];
if (oForm2Element.value == '')
{
    oForm2Element.value += oForm1Element.value;
}
else
{
    oForm2Element.value += ', ' + oForm1Element.value;
}

We first acquire references to form objects using their names. We then acquire references to the source and target elements, again using the element names. Thereafter, it is an easy job to copy the value of the source element to the target element.

Download the code.

Be Sociable, Share!
  • Novice

    thanks .. it helped me a lot to save my time…..

  • Erx

    you should mention that whenever you use the .elements collection, that it will ALWAYS EXCLUDE, AND NEVER RETURN an input type=image element (apparently for backwards compatibility.

    so, if you use form[n].elements, you will never be able to get a reference to the following returned…

    INPUT TYPE=”IMAGE”

    it just ignores it, like it wasn’t there. for this reason it is better to use document.ALL or frame[n].ALL – i’m pretty sure the getElementBy**** methods should return the INPUT TYPE=IMAGE elements (but don’t quote me on that).

    look for the .elements collection on msdn’s dom pages, and it states it there. i was shocked when i heard this and went looking through past code and luckily i hadn’t been using it anywhere where i needed a reference to input type=image … i would love for you to talk about this or address this somewhere – and if you have time to do some testing to figure out where it works and where it doesn’t i’d be happy to hear, since i am going to do some testing myself and would be happy to report back on this if you would like me to.

    let me know, cheers.

  • Rob Smith

    Thanks for the post. I am still having some difficulty with applying multiple forms in the one html file.

    I have 3 forms in my current page that require some user input to calculate various amounts. Javascript is being used to calculate the values for all three forms. At the bottom of each form there is a calculate button. So I have 3 buttons, one for each form.

    The first form calculates perfectly. However, when I hit the calculate button on the second and third form nothing happens.

    I am using the onclick=calculate(this.form) event handler.

    Apologies I can’t submit the code its proprietary and I am looking at it on behalf of someone else.

  • http://aspconsultant.com Mike Bragunier

    Thanks so much. Made a lot of sense and solved my problems. You’re helping me go from hacking javascript to coding javascript.

  • Ben_the_fat_banker

    Thanks for this :) Helped me solve a problem that was taking far too much of my time…KUDOS!!

Previous post:

Next post: