Working with JavaScript's document.forms Property

The document.forms property in JavaScript is a powerful tool for accessing and interacting with forms in an HTML document.

document.forms.

This property, a key part of the document object and the Document Object Model (DOM), enables seamless interaction with forms on a webpage.

It acts as an interface, specifically an HTMLCollection, that compiles details about every form embedded within the page.

Why is it useful? It allows for iterating over the collection, accessing each form either by its index or name, and manipulating forms and their elements (like inputs and textareas) through JavaScript. This enhances web pages, making them more interactive and user-friendly.

Imagine we have a login form on our HTML page labeled "loginForm".

<html>
<body>
<form id="loginForm" name="login">
Username: <input type="text" name="username" />
Password: <input type="password" name="password" />
<input type="submit" />
</form>
<script>
// Accessing the form by name
var form = document.forms['login'];
// Processing the form object
</script>
</body>

Here, the script taps into the "login" form content via forms['login'] and assigns it to a variable "form", treating it as an HTMLFormElement object.

Having accessed the form, it's possible to manipulate it further, setting values for its fields as necessary.

For a cleaner approach to accessing form content, one might prefer:

var form = document.forms.login;

Alternatively, accessing the form by its ID is just as straightforward:

var form = document.getElementById('loginForm');

Example Use Case

Let's consider a scenario where we want to verify that both username and password fields are filled out before the form is submitted.

Here's how we might implement that:

<script>
document.forms['login'].onsubmit = function() {
var username = document.forms['login']['username'].value;
var password = document.forms['login']['password'].value;

if (!username || !password) {
alert('Please make sure both username and password are entered.');
return false; // Stops the form from submitting
}
// If checks pass, proceed with form submission
return true;
};
</script>

In this straightforward example, a function is linked to the form's "onsubmit" event, ensuring data validation before submission.

To figure out the number of forms in a document, the length attribute comes in handy.

<script>
let num = document.forms.length;
document.getElementById("demo").innerHTML = 'Number of forms: ' + num;
</script>

This function checks for empty username and password fields, providing an error message and blocking the form submission if necessary.

And that's just scratching the surface.

 
 

Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

FacebookTwitterLinkedinLinkedin
knowledge base

Javascript