JavaScript – Forms

Javascript and Forms

In javascript for every <form> </form> tags, a form object is created. Then We can access the form and its elements.

The first method is to use forms array. The forms array allows access to a form using index. Each <form> element of HTML document will be an item in forms array. Thus in order to access the first set of <form> tag we can use:

document.forms[0]

The form that is accessed is an object which has its own properties and methods.

 

The second method is to use form names. To use form name, the name attribute must be specified in the HTML <form> tag. For example:

<form name=”f1”>

<input type=”text” name=”sname” />

</form>

In the above code the name of the form is “f1”. Thus the name of the form can now be used with the document object to access its elements. For example:

document.f1

 

The third method is to use ID attribute. To use this method id attribute must be specified for every element in the HTML <form> tag. We can now use getElementById() to access the elements of the <form> tag. This method is the commonly used, and is the most clean way of accessing form and its elements, because each element can be accessed by its individual id attribute. The first and second method is cumbersome, since it requires us to know the index as well as the form name and its elements names.

<form id=”f1”>

<input type=”text” name=”sname” />

</form>

var frm = document.getElementById(“f1”);

 

The form object has a property known as elements property. The elements property is an array that allows us to access each element within a specific form in the same order it appears in the HTML code. The index of elements array starts with 0. The element of the <form> tag can be accessed by using the index number of the element. For example:

<form name=”f1” id=”f1”>

<input type=”text” name=”sname” id=”snid” />

<input type=”submit” name=”sub” id=”subid” />

</form>

The above HTML <form> code has two elements, one is the textbox and the other is the submit button with name and id attributes. To access the textbox element we can use:

document.forms[0].elements[0];

document.f1.elements[0];

document.f1.sname;

document.getElementById(“snid”);

 

The form object also has methods such as submit() which allows us to submit a form without user clicking the submit button. It also has a reset() method which enables us to reset the form within the script. For example:

var frm = document.getElementById(“f1”);

frm.submit();

frm.reset();