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
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
Let us look at each of these methods of accessing multiple forms in details.
this.form to the onClick event handler of a form button.
<form name ="myform" action="#"> Name: <input type="text" name="myname" size="50"> Email: </label><input type="text" name="email" size="50"> Phone: <input type="text" name="phone" size="50"> <input type="button" name="go" value="Go" onclick="showElements(this.form);"> </form>
this refers to the button object, and
this.form references the form object. This form object can be used in the
showElements function to access the form and all its elements.
How to access multiple Forms using the document object’s forms collection
The document object of a page has an array
forms which holds references to all the form objects on that page. We can get references to individual forms by using the index or names. Index begins at 0.
For eg., if we have two forms with names as “firstform” and “secondform” respectively, we can access the form named “firstform” in the following two ways:
var oForm = document.forms; //OR var oForm = document.forms["firstform"];
We could also use the shorthand notation: document.formname:
var oForm = document.firstform;
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
To access the text input field named “tags_list” of the form named “submit_bookmark”, we can use one of the following methods:
var oForm = document.forms["submit_bookmark"]; var oTagsList = oForm.elements; //OR var oTagsList = oForm.elements["tags_list"]; //Get the value of the input element, var tags = oTagsList.value;
As a further example, let us say that we had to copy the value of an element in one form into an element in another form.
Here, we first acquire references to form objects using their names. We then acquire references to the source and target elements. Then, copy the value of the source element to the target element.