Tips and Tricks on Web and Technology

Access Form objects in case of multiple forms

How to access form objects in case of multiple forms, using JavaScript?

Assume, we have a form with the id “myform”, then form can be accessed by:

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

This method can only be used only when the <form> tag has an id attribute.

Another way to do it without id attribute set to form tag is, by using this keyword. Get a reference to the form object, through the this.form property (even if there are multiple forms on the page).

Another way is to use the document object’s forms collection. The forms collection is a Javascript array that holds references to all the forms in a web page. Each form reference can be accessed either by its index in this array or by its name attribute.

Let us look at each of these methods of accessing multiple forms in details.

How to access multiple Forms through Javascript using the this.formproperty?

Note: The shorthand notation is deprecated, and is either not supported in recent versions of Firefox or is buggy and unreliable.

It is also preferable to use the form’s name attribute instead of the index, as it is less likely for the name of the forms on the page to change, and more likely for their sequential position in the code to change.

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”, we can use one of the following methods: