HTML Document forms Collection: Accessing Form Elements

The document.forms collection in HTML provides a powerful way to access all <form> elements within an HTML document using JavaScript. This collection is an HTMLCollection, meaning it’s an array-like structure that contains all forms defined on a page, allowing you to manipulate and interact with them dynamically. Understanding how to use this collection is crucial for handling user input and building interactive web forms. This article will walk you through the syntax, usage, and examples of the document.forms collection.

What is document.forms?

The document.forms property is a read-only collection that returns an HTMLCollection of all the <form> elements present in the HTML document. It allows you to access these form elements either by their index in the collection or by their name or ID. This makes it incredibly easy to work with form data and behaviors using JavaScript.

Purpose of document.forms

The primary purpose of the document.forms collection is to:

  • Access Forms: Retrieve all form elements on a web page.
  • Manipulate Forms: Modify form properties, attributes, and content.
  • Handle Form Data: Access and process user inputs from form controls.
  • Validate Forms: Implement custom validation logic before submitting form data.
  • Control Form Behavior: Dynamically change form actions, methods, and submissions.

Syntax and Usage

The document.forms property is accessed directly from the document object. Here’s the basic syntax:

const formsCollection = document.forms;

The formsCollection variable will hold an HTMLCollection of all forms in the document. You can then access specific forms using their index, name, or ID.

Accessing Forms by Index

Forms are indexed in the order they appear in the HTML document, starting from 0.

const firstForm = document.forms[0]; // Access the first form
const secondForm = document.forms[1]; // Access the second form

Accessing Forms by Name or ID

If a form has a name or id attribute, you can access it using these attributes as keys.

<form id="myForm" name="userForm">
  <!-- Form elements here -->
</form>
const formById = document.forms["myForm"];
const formByName = document.forms["userForm"];

Important Properties of Form Elements

Understanding the properties of individual form elements is crucial for effective use:

Property Type Description
`action` String Sets or returns the value of the form’s action attribute.
`elements` HTMLFormControlsCollection Returns a collection of all form controls within the form.
`encoding` String Sets or returns the value of the form’s enctype attribute.
`enctype` String Sets or returns the value of the form’s enctype attribute.
`length` Number Returns the number of controls in a form.
`method` String Sets or returns the value of the form’s method attribute.
`name` String Sets or returns the value of the form’s name attribute.
`target` String Sets or returns the value of the form’s target attribute.
`reset()` Function Resets the form to its initial values.
`submit()` Function Submits the form.

Note: Always ensure that forms are either given a unique name or ID to avoid conflicts. ⚠️

Basic Examples

Let’s explore some basic examples of how to use the document.forms collection. Each example includes the necessary HTML and JavaScript code to interact with form elements.

Accessing a Single Form

This example demonstrates how to access a form by its ID and display its action attribute.

<form id="myFormExample" action="/submit">
  <input type="text" name="username" />
  <button type="submit">Submit</button>
</form>

<p id="formAction"></p>

<script>


  const formEx = document.forms["myFormExample"];
  const actionDisplay = document.getElementById("formAction");
  actionDisplay.textContent = "Form action is: " + formEx.action;


</script>

Output:

Form action is: /submit

Getting the Number of Forms

This example shows how to get the total number of forms on a page using the length property of the document.forms collection.

<form id="form1"></form>
<form id="form2"></form>
<p id="formCount"></p>

<script>


  const formsCount = document.forms.length;
  document.getElementById("formCount").textContent =
    "Number of forms: " + formsCount;


</script>

Output:

Number of forms: 2

Accessing Form Elements

This example demonstrates how to access form elements within a specific form.

<form id="myFormElements">
  <input type="text" name="firstName" value="John" />
  <input type="text" name="lastName" value="Doe" />
</form>

<p id="elementValues"></p>

<script>


  const formElementEx = document.forms["myFormElements"];
  const firstName = formElementEx.elements["firstName"].value;
  const lastName = formElementEx.elements["lastName"].value;
  document.getElementById("elementValues").textContent =
    "First Name: " + firstName + ", Last Name: " + lastName;


</script>

Output:

First Name: John, Last Name: Doe

Iterating Over All Forms

This example demonstrates how to iterate over all forms in a document using a for...of loop and print the names or ids of each form.

<form id="formA" name="firstForm"></form>
<form id="formB"></form>

<ul id="formList"></ul>

<script>


    const formListEx = document.getElementById('formList');
    for(const form_item of document.forms){
        let formNameOrId = form_item.name ? form_item.name : form_item.id;
        const listItem = document.createElement('li');
        listItem.textContent = `Form name or id: ${formNameOrId}`;
        formListEx.appendChild(listItem);
    }


</script>

Output:

  • Form name or id: firstForm
  • Form name or id: formB

Advanced Examples

Dynamically Setting Form Attributes

This example demonstrates how to dynamically change form attributes, such as the action attribute using javascript.

<form id="dynamicForm" action="/original">
  <button onclick="changeAction()">Change Action</button>
</form>
<p id="dynamicAction"></p>

<script>


  function changeAction() {
    const dynamicFormEx = document.forms["dynamicForm"];
    dynamicFormEx.action = "/newSubmit";
      document.getElementById("dynamicAction").textContent = "Form action changed to " + dynamicFormEx.action;
  }


</script>

Output: (Click the button to see the action change)

Form action changed to /newSubmit

Resetting Form Fields

This example demonstrates how to reset all fields within a form.

<form id="resetForm">
    <input type="text" name="resetInput" value="Initial Value" />
    <button onclick="resetFields()">Reset</button>
    </form>
<p id="resetResult"></p>

<script>


  function resetFields() {
      const resetFormEx = document.forms["resetForm"];
        resetFormEx.reset();
        const resetInputValue = resetFormEx.elements["resetInput"].value;
        document.getElementById("resetResult").textContent = "Form input value is: " + resetInputValue;

  }


</script>

Output: (Click the button to reset the form and see the result)

Form input value is:

Submitting the Form

This example will demonstrate the use of javascript to submit the form.

<form id="submitForm" action="/submit">
    <input type="text" name="submitInput" value="Test Input">
    <button onclick="submitForm()">Submit</button>
</form>
<p id="submitResult"></p>

<script>


  function submitForm() {
    const submitFormEx = document.forms["submitForm"];
        submitFormEx.submit();
        document.getElementById("submitResult").textContent = "Form is submitted!";
  }


</script>

Output: (Click the button to see the form submit)

Form is submitted!

Note: The form submit will reload the page for the example. 📝

Real-World Applications of the document.forms Collection

The document.forms collection is used in various real-world scenarios, including:

  • Form Validation: Validating form data before submission to ensure accuracy.
  • Dynamic Form Manipulation: Dynamically showing or hiding form fields based on user input.
  • Form Data Processing: Collecting and processing form data for further use.
  • Accessibility: Enhancing form accessibility for users with disabilities.
  • Custom Interactive Forms: Creating highly interactive and dynamic forms.

Browser Support

The document.forms collection is well-supported by all modern web browsers, ensuring that your web forms will function consistently across various platforms.

Note: Always test your form functionalities across different browsers and devices to ensure a seamless user experience. ✅

Conclusion

The document.forms collection is a fundamental tool for accessing and manipulating HTML forms in JavaScript. It provides a flexible and efficient way to interact with form elements, enabling you to build dynamic, responsive, and user-friendly web applications. This comprehensive guide has equipped you with the knowledge to use this collection effectively in your web development projects. Remember to use unique names or IDs for each form to prevent any conflict. Happy coding!