Creating Interactive Forms Using JavaScript

Forms play an integral role in web development. They allow users to provide data, make transactions with the sites, and carry out other functions, for example, signing up or in, giving feedback and so on. Creating forms has been made a piece of cake by HTML, however, the most interesting bits in creating forms are made possible by the use of Javascript. This means that forms created using Javascript can have moving parts, for example, elements inside the form can be changed, validated, or updated depending on the user's interactions. In this article, we will dive deeper into the world of Javascript and see how it can be applied to make forms more engaging.

Deciphering the Anatomy of a Form

As far as HTML is concerned, a typical form has a number of input elements such as text boxes, radio buttons, check boxes, a drop box and a submit button. Such elements are all enclosed within a tag called `
`. The primary objective of a form is to gather user details, which is why the ` ` tag also has the `action` and `method` attributes that help to identify where and how the details provided in the form will be forwarded once the form is submitted. But for a form to be engaging then Javascript has to be implemented.

We'll work with the HTML form:

Basic HTML Form

  <form id="contactForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>


The HTML code above demonstrates a basic form with input fields for a name, email, and a submit button. The way the functionality is designed very simply, when the data is filled, the page gets refreshed and the information filled in the form is sent over. But thanks to JavaScript we have a chance to reshape it.

Enhancing Usability Through Javascript

It provides a structural base however forms are made interactive using JavaScript. Within the JavaScript, tasks can be set in order such as form input requirement checking, auto filling forms, and content replacement or adding without reloading the page.

1. Filling out the Form

Filling the form allows the users to put in relevant information and is completed after the requirements are checked. Before you send the filled in form to the server. Some of the things to look out for are making sure all required fields have some values filled in and/or the email address is in a valid format. And this is where the use of JavaScript comes along.

Form Validation Example

  document.getElementById("contactForm").addEventListener("submit", function(event) {
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;
if (name === "" || email === "") {
event.preventDefault();
alert("All fields must be filled out.");
}
});


In the above examples , the `submit` event listener checks the name and email before sending the form, so these fields are not empty. If there is any blank space on the name and email field , the `event.preventDefault()` method will cancel the submission of the form using an alert.


2. Input feedback on real-time basis

Apart from checking the validation of the form after the submission, form submission can also be a feature which allows to give feedback on real time to the users while they are filling the form, for instance highlighting correctly filled fields or where the user has filled in data incorrectly, or even providing feedback on whether the user's email address is correct or not.

Real-Time Email Validation Example

  document.getElementById("email").addEventListener("input", function() {
let email = this.value;
let emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,6}$/;
if (emailPattern.test(email)) {
this.style.borderColor = "green"; // Valid email
} else {
this.style.borderColor = "red"; // Invalid email
}
});


This script takes into consideration the validity of the email format when a user changes the email input. In case the email structure is corrected the border of the email input will be colored green, in the opposite case the border will be red. This will not only help users comply with the format but also visualize what is needed.

3. Adaptive Form Fields

Java,Script must be the code,among other the code which enables form fields to be usably altered through inserting key elements. For instance, if a customer wishes other fields to appear on the form, they can, in turn, add/subtract fields.

Adaptive Form Fields Example

  document.getElementById("newsletter").addEventListener("change", function() {
let newsletterField = document.getElementById("newsletterType");
if(this.value =="yes") {
newsletterField.style.display = "block"; // Show newsletter type field
} else {
newsletterField.style.display = "none"; // Hide it if "No" is selected
}
});


In this scenario, the consumers specify whether they wish to receive the newsletter, in which case a new field requesting them to specify the type of newsletter they would like to receive appears. It is the capability of JavaScript that makes this kind of dynamic change without refreshing the page.

4. Submission of Form

After all the required fields in the form have been filled and the form data validated then you can proceed to getting the form submitted. In the conventional way, sending a form would imply sending the data to the server and the page being reloaded; with the help of JavaScript this is not necessary, it is now possible to send the form data even without reloading the page enabling better user experience.

AJAX Form Submission Example

  document.getElementById("contactForm").addEventListener("submit", function (event) {
event.preventDefault();
const formData = new FormData(this);
fetch("/submit-form", {
method: "POST",
body: formData
})
.then((response) => response.json())
.then((data) => {
alert("Submit form successfully!");
})
.catch((error) => {
alert("An error occurred in course of submission.");
});
});


In this case after a form was submitted, its data was sent to the server using the `fetch` method without refreshing the browser. As a result the user gets a success or error message depending on what the server sends back.