Working with Form Objects in JavaScript

Introduction

Forms are an integral part of web development, serving as the primary interface for user input. Whether it's collecting data, processing transactions, or facilitating user interactions, forms are everywhere on the web. JavaScript, with its robust capabilities, provides developers with powerful tools to manipulate and enhance form behavior. By working with form objects in JavaScript, developers can dynamically control the user experience—validating input, submitting data asynchronously, or even altering form elements on the fly. Understanding how to interact with form objects using JavaScript not only enhances the functionality of web applications but also improves usability and accessibility for users.

This introduction will guide you through the basics of working with form objects in JavaScript, laying the foundation for creating more responsive and interactive web forms.

For example

The following program code is a good example to show how form events are handled in JavaScript. It displays a form having the following components.

  • The text field “First Name” to accept the user’s first name.
  • The text field “Last Name” accepts the user’s last name.
  • Text field “Email Address” to accept the user’s email address.
  • Text area “Comments” for the user’s comments.
  • “Submit This Form” button and “Reset this form” button.

This program takes care of the following validations.

When the user clicks on the “Submit This Form” button, the contents are validated and displayed in a new window. Similarly, when the user clicks on the “Reset This Form” button, the contents in the form fields are reset.

<html>
<head>
<title>Form Events</title>
<script language="JavaScript">
function IsBlank(s) {
    var len = s.length;
    for (var i = 0; i < len; i++) {
        if (s.charAt(i) != " ") {
            return false;
        }
    }
    return true;
}
function validate_LastName() {
    var str = document.form1.lname.value;
    if (IsBlank(str)) {
        alert("The last name field cannot be empty");
        return false;
    }
    return true;
}
function Validate_FirstName() {
    var str = document.form1.fname.value;
    if (IsBlank(str)) {
        alert("The first name field cannot be empty");
        return false;
    }
    return true;
}
function Validate_Email() {
    var str = document.form1.email.value;
    if (IsBlank(str)) {
        alert("The email field cannot be empty");
        return false;
    }
    if (IsValid()) {
        return true;
    }
    return false;
}
function IsValid() {
    var str = document.form1.email.value;
    var len = str.length;
    for (var i = 1; i < (len - 3); i++) {
        if (str.charAt(i) == "@") {
            return true;
        }
    }
    alert("You have entered an invalid E-Mail Address");
    return false;
}
function processForm() {
    if (!Validate_FirstName(document.form1.fname.value)) return false;
    if (!validate_LastName(document.form1.lname.value)) return false;
    if (!Validate_Email(document.form1.email.value)) return false;
    if (!IsValid()) return false;    
    var disp = open(" ", "result");
    disp.document.write("<TITLE>Result Page</TITLE><PRE>");
    disp.document.write("<H2 ALIGN='CENTER'>Thanks for SignIn</h2><hr><br><br>");
    disp.document.write("FirstName\t\t:" + document.form1.fname.value + "<br>");
    disp.document.write("LastName\t\t:" + document.form1.lname.value + "<br>");
    disp.document.write("E-Mail Address\t\t:" + document.form1.email.value + "<br>");
    disp.document.write("Your Comments\t\t:" + document.form1.comment.value + "<br>");
    disp.document.write("</PRE>");
    
    if (disp.confirm("Is this information correct?")) {
        disp.close();
    }
}
</script>
</head>
<body>
<h2 align="center">Handling Form Events</h2><hr>
<form name="form1">
    <p>First Name: <INPUT TYPE="TEXT" NAME="fname" MAXLENGTH="10" ONCHANGE="Validate_FirstName()">
    Last Name: <INPUT TYPE="TEXT" NAME="lname" MAXLENGTH="15" ONCHANGE="validate_LastName()"></p>
    
    <p>E-Mail Address: <INPUT TYPE="TEXT" NAME="email" MAXLENGTH="30" ONCHANGE="Validate_Email()"></p>
    <p>Comments: <TEXTAREA NAME="comment" ROWS="4" COLS="30" ONFOCUS="document.form1.comment.select()">Enter your Comments</textarea></p>
    
    <p align="center">
        <input type="Button" value="Submit This Form" ONCLICK="return processForm()">
        <input type="RESET" value="Reset This Form">
    </p>
</form>
</body>
</html>

Output

Output

Result page

Description About the source code

This HTML document is designed to capture user information through a form, specifically gathering the user's first name, last name, email address, and comments. To ensure the integrity of the submitted data, the form leverages JavaScript for input validation, making sure that all fields are filled out correctly and that the email address adheres to a valid format. The form consists of several input fields, including text fields for the first and last names, an email input field, and a text area for additional comments. The JavaScript functions play a crucial role in validating these inputs.

The `IsBlank` function checks if a given string is empty or consists solely of spaces, which is then utilized by other validation functions like `validate_LastName`, `Validate_FirstName`, and `Validate_Email`. Each of these functions ensures that the respective form field is not left empty, displaying an alert and preventing form submission if any issues are detected. The `Validate_Email` function takes this a step further by confirming that the email field is not only filled but also formatted correctly, using the `IsValid` function to check for the presence of the `@` symbol, which is essential for a valid email address. The `processor` function orchestrates the overall validation and submission process. It sequentially calls the validation functions for the first name, last name, and email fields, and if any field fails validation, it halts the submission process, prompting the user to correct the errors. If all fields pass validation, the form data is displayed in a new window, allowing the user to review the information.

This review window asks the user to confirm that the details are correct before final submission, providing an additional layer of verification. The form also includes event handlers such as `onchange`, which triggers validation when the content of a field changes, and `ONFOCUS`, which automatically selects the text within the comments textarea when it is clicked. The submit button is linked to the `processForm` function, initiating the validation process when clicked, while a reset button is available to clear all fields if necessary. Overall, the form is structured to ensure that users submit complete and correctly formatted information, reducing the chances of errors and improving the reliability of the data collected.

Summary

This HTML document incorporates a user input form that collects first name, last name, email address, and comments. JavaScript functions are used to validate the form fields, ensuring that no fields are left blank and that the email address is correctly formatted. The validation process includes checks for empty fields and the presence of an `@` symbol in the email address. If all inputs are valid, the form data is displayed in a new window for the user to review and confirm before submission. This setup enhances the reliability and accuracy of the data collected, preventing common form submission errors.

  1. The “First Name” and the “Last Name” fields cannot be blank.
  2. The user has to enter a valid email address in the “Email Address field.