Assume, we have a form with the id “myform”, then the 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 attribute set to form tag is, by using keyword. Get a reference to the form object, through the
this.form property (even if there are multiple forms on the page).
Let us look at each of these methods of accessing multiple forms in detail.
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 references the form object. This form object can be used in the 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 that holds references to all the form objects on that page. We can get references to individual forms by using the index of names. The index begins at 0.
For eg., if we have two forms with names as “first form” and “second form” respectively, we can access the form named “first form” in the following two ways:
var oForm = document.forms; //OR var oForm = document.forms["firstform"];
We could also use the shorthand notation: document.forename:
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.