How to work with document.forms in JavaScript?


In this tutorial, let us discuss how to work with document.forms in JavaScript.

The document.form property returns all the form tags in the document. The forms property is read-only. The form property is the Dom level 1 feature.

Working with form attributes and elements

Here let us learn to work with a form's properties, attributes, and elements.

Users can follow the syntax below to work with the form's properties and elements.

Syntax

var forms = document.forms;
let formLen = forms.length;
let formId = forms[0].id || forms.item(0).id;
let formItemId = forms[0].elements[0].id;
let formItemVal = forms[0].elements[0].value;
let formData = forms.namedItem("testForm").innerHTML;

The above syntax returns the collection of forms, the total number of forms, form id, form element id, form element value, and form content in order.

Properties

  • length − The length is the number of elements in an HTML collection.

Methods

  • [index] − The index method returns the element at the specific position. The index starts from zero. The method returns "null" if the index is out of range.

  • item(index) − Returns the element at the specific position. The index starts from zero. The method returns "null" if the index is out of range.

  • namedItem(id) − Returns the element with the specific id. The method returns "null" if the id is wrong.

Return Value

The form property returns the HTML form object collection. The object follows the source code order.

Example

In this program, we display the total number of forms, form id, form element id, form element value, and form content of a form in the document.

<html> <body> <h2>Working with the document object.forms properties and elements</h2> <div id = "formPropBtnWrap"> <form name = "testForm" id="testFormId"> <p>Name: <input type = "text" name = "name" value = "Egan" id = "testFormItemId"></p> <p>Job: <input type = "text" name = "job" value = "Handicapper"></p> </form> <p>Click the button to see the properties</p> <button onclick = "getFormProp()">Click Me</button> </div> <p id = "formPropOut"></p> <script> function getFormProp() { var forms = document.forms; let formLen = forms.length; let formId = forms[0].id || forms.item(0).id; let formItemId = forms[0].elements[0].id; let formItemVal = forms[0].elements[0].value; let formData = forms.namedItem("testForm").innerHTML; var formPropBtnWrap = document.getElementById("formPropBtnWrap"); var formPropOut = document.getElementById("formPropOut"); var formPropStr = ""; // formPropBtnWrap.style.display = "none"; formPropStr += "Total forms = " + formLen + "<br><br>"; formPropStr += "First form id = " + formId + "<br><br>"; formPropStr += "First form first item id = " + formItemId + "<br><br>"; formPropStr += "First form first item value = " + formItemVal + "<br><br>"; formPropStr += "<b>First form data = </b>" + formData + "<br><br>"; formPropOut.innerHTML = formPropStr; } </script> </body> </html>

Working with form methods

Here let us learn to work with a form's methods.

Users can follow the syntax below to work with the form's methods.

Syntax

var forms = document.forms;
let formObj = forms.colors;
formObj.submit();
formObj.reset();

The above syntax returns the collection of forms, a form with the name "colors". The last two lines of code denote form submit and form reset, respectively.

Example

In this program, we access a form with its name, and the function performs the form submit and form reset upon user request.

<html> <head> <title>JavaScript String match() Method</title> </head> <body> <script> // all the variables declared at top var str, re, found; str = "For more information, see Chapter 3.4.5.1"; re = /(chapter \d+(\.\d)*)/i; found = str.match( re ); document.write(found ); </script> </body> </html>

Example 2

We have taken user values in the example below and displayed them separately on the page. We have declared two variables at the top, one in the middle, and one at the end. You can see in the program that the variables declared at the top makes the code neat and more readable. At the same time, variables are declared in the middle making it more complex. In the following code, by mistake, we have initialized another variable called k instead of j, making j a non-initialized variable. Because of not adding a variable at the top, we have forgotten that an unnecessary variable is left behind in the code called 'l'.

<html> <head> <style> p { color: red; } </style> </head> <body> <h2>Is it a good practice to place all declarations at the top in JavaScript?</h2> <label for = "top_var"> Variable declared at top:</label> <input type = "text" id = "top_var" name = "Top" value = " " /><br> <label for = "middle_var"> Variable declared at Middle:</label> <input type = "text" id = "middle_var" name = "Middle" value = " " /><br> <label for = "end_var"> Variable declared at End:</label> <input type = "text" id = "end_var" name = "End" value = " " /><br> <button id = "btn">submit</button> <div id = "div"></div> <script> var element, i; document.getElementById("btn").addEventListener("click", practice); function practice() { element = document.getElementById("div"); i = document.getElementById("top_var").value; var text = document.createTextNode(" Variable declared at top: " + i); var para1 = document.createElement('p'); para1.appendChild(text); var j; k = document.getElementById("middle_var").value; var text1 = document.createTextNode(" Variable declared at middle: " + j); var para2 = document.createElement('p'); para2.appendChild(text1); var k; k = document.getElementById("end_var").value; var text2 = document.createTextNode(" Variable declared at last: " + k); var para3 = document.createElement('p'); para3.appendChild(text2); element.appendChild(para1); element.appendChild(para2); element.appendChild(para3); var l; } </script> </body> </html>

In the above example, users can see that placing all declarations at the top in JavaScript is a good practice.

Example 3

In the example below, we have input from the user and converted it into an array, and all elements of an array are saved in different variables. You can see in the following program that all the variables used in the program are declared in the first line after the script tag. This helps reduce the code's length and our efforts of adding 'var' for every variable. We added a bunch of variables at the top and accessed that as a dynamic variable using the eval() method inside the loop.

<html> <head> <style> p { color: red; } </style> </head> <body> <h2>Is it a good practice to place all declarations at the top in JavaScript?</h2> <label for = "arr_Elements"> Add array elements seperated by space: </label> <input type = "text" id = "arr_Elements" name = "element" value = " " placeholder = "5 elements max" /> <br> <button id = "btn">submit</button> <div id = "div"></div> <script> var element, value, arr, i, j, a, a1, a2, a3, a4, a5, para; document.getElementById("btn").addEventListener("click", add_Elements); element = document.getElementById("div"); function add_Elements() { value = document.getElementById("arr_Elements").value; arr = value.split(" "); for (i=1; i<=arr.length; i++) { if (arr[i - 1] != "") { eval('a' + i + "=" + arr[i - 1] + ";"); para = document.createElement('p'); console.log(a1); para.innerHTML = " Value of " + 'a' + (i - 1) + ": " + eval('a' + i); element.appendChild(para); } else { } } } </script> </body> </html>

In the above example, users can see that adding declarations at the program's top becomes more readable and saves the programmer's effort. That's why placing all declarations at the top in JavaScript is a good practice.

In this tutorial, we have learned a good practice of where to place all declarations in JavaScript. Placing the declarations at the top has always been a good practice in JavaScript.

Updated on: 31-Oct-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements