Skip to main content

Form Handling in JavaScript

This article is a complementary resource to the JavaScript in Browser course.

Form Handling in JavaScript

Forms are a crucial component of web applications, enabling users to interact with websites by entering and submitting data.

JavaScript provides powerful tools for handling form data, validating user inputs, and creating dynamic, interactive forms.

In this article, you'll learn the fundamentals of JavaScript form handling with the help of practical examples.


Getting Values from Form Elements

JavaScript allows you to easily access the values entered by users in form elements. These include:

  • Text inputs (using the value property)
  • Checkboxes (using the checked property)
  • Radio buttons (using the checked and value properties)
  • Select dropdowns (using the value property)

Let's go through them one by one.


Text Inputs

We use the value property to get or set the text entered in text input fields. For example, consider the following HTML code:

HTML Code

<input type="text" id="username" name="username" value="Initial Value">

Here's how you can use JavaScript to get and set the text value:

JavaScript Code

let username = document.querySelector("#username").value;
console.log(username); // Prints initial value of the text

// Setting a new value
document.querySelector("#username").value = "New User";

Checkboxes

For checkboxes, the checked property indicates whether the checkbox is selected.

HTML Code

<input type="checkbox" id="agree" name="agree">
<label for="agree">I agree to the terms</label>

JavaScript Code

let isAgreed = document.querySelector("#agree").checked;
console.log(isAgreed); // Outputs: true if checked, false otherwise

Radio Buttons

Radio buttons require checking the checked property to determine which button is selected and accessing its value.

HTML Code

<input type="radio" id="option1" name="options" value="1">
<label for="option1">Option 1</label>

<input type="radio" id="option2" name="options" value="2">
<label for="option2">Option 2</label>

JavaScript Code

let selectedOption = document.querySelector('input[name="options"]:checked').value;
console.log(selectedOption); // Outputs: 1 or 2 depending on selection

Select Dropdowns

The value property of a select element provides the value of the selected option.

HTML Code

<select id="city" name="city">
    <option value="newyork">New York</option>
    <option value="london">London</option>
    <option value="paris">Paris</option>
</select>

JavaScript Code

let selectedCity = document.querySelector("#city").value;
console.log(selectedCity); // Outputs: newyork, london, or paris

Handling Form Submission

The submit event is triggered when a form is submitted. You can use JavaScript to handle this event and perform actions such as preventing the default submission behavior and accessing form data.

Preventing Default Behavior with event.preventDefault()

The default behavior of a form submission is to navigate to the URL specified in the action attribute or reload the page if no action is specified. To prevent this, use event.preventDefault().

HTML Code

<form id="myForm">
    <input type="text" id="name" name="name"><br><br>
    <button type="submit">Submit</button>
</form>

JavaScript Code

document.querySelector("#myForm").addEventListener("submit", function(event) {
    event.preventDefault();
    console.log("Form submission prevented!");
});

Accessing Form Data on Submission

You can access form data within the submit event handler using the value property of the form elements.

HTML Code

<form id="myForm">
    <label for="email">Email:</label>
    <input type="email" id="email" name="email"><br><br>
    <button type="submit">Submit</button>
</form>

JavaScript Code

document.querySelector("#myForm").addEventListener("submit", function(event) {
    event.preventDefault();
    let email = document.querySelector("#email").value;
    console.log("Email submitted:", email);
});

Example: Preventing Default Form Submission

This example demonstrates how to prevent the default form submission and log the form data to the console.

<!DOCTYPE html>
<html>
<head>
    <title>Form Submission Example</title>
</head>
<body>
    <form id="myForm">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name"><br><br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email"><br><br>
        <button type="submit">Submit</button>
    </form>

    <script>
        document.querySelector("#myForm").addEventListener("submit", function(event) {
            event.preventDefault();
            let name = document.querySelector("#name").value;
            let email = document.querySelector("#email").value;
            console.log("Name:", name, "Email:", email);
        });
    </script>
</body>
</html>

Validating Form Inputs

Form validation is essential for ensuring that user-provided data meets the required criteria.

JavaScript allows you to perform various types of validation on the client side before submitting the form.

Types of Validation

  1. Required Fields: Check if mandatory fields are filled in.
  2. Email & Pattern Validation: Verify that email addresses and other inputs match a specific format.
  3. Number and Range Checks: Ensure that numeric inputs fall within a specified range.

Custom Validation with JavaScript

You can implement custom validation logic using JavaScript to check for specific conditions.

Using setCustomValidity() and checkValidity()

  1. setCustomValidity() - Sets a custom error message for an input element.
  2. checkValidity() - Checks if the input element has any validity constraints and returns a Boolean value.

HTML Code

<input type="email" id="email" name="email" required>

JavaScript Code

let email = document.querySelector("#email");

email.addEventListener("input", function() {
    if (email.validity.typeMismatch) {
        email.setCustomValidity("Please enter a valid email address.");
    }
    else {
        email.setCustomValidity(""); // Clear the error message
    }
});

Displaying Error Messages Dynamically

Display error messages dynamically to provide real-time feedback to users.

HTML Code

<form id="myForm">
    <label for="age">Age:</label>
    <input type="number" id="age" name="age" min="18" max="99"><br>
    <span id="ageError" style="color: red;"></span><br>
    <button type="submit">Submit</button>
</form>

JavaScript Code

document.querySelector("#myForm").addEventListener("submit", function(event) {
    let age = document.querySelector("#age");
    let ageError = document.querySelector("#ageError");

    if (age.value < 18 || age.value > 99) {
        event.preventDefault();
        ageError.innerText = "Age must be between 18 and 99.";
    } else {
        ageError.innerText = ""; // Clear the error message
    }
});

Example: Validating an Email Field

This example demonstrates how to validate an email field to ensure it contains the @ symbol.

<!DOCTYPE html>
<html>
<head>
    <title>Email Validation Example</title>
</head>
<body>
    <form id="myForm">
        <label for="email">Email:</label>
        <input type="email" id="email" name="email"><br>
        <span id="emailError" style="color: red;"></span><br><br>
        <button type="submit">Submit</button>
    </form>

    <script>
        document.querySelector("#myForm").addEventListener("submit", function(event) {
            let email = document.querySelector("#email");
            let emailError = document.querySelector("#emailError");

            if (!email.value.includes("@")) {
                event.preventDefault();
                emailError.innerText = "Please enter a valid email!";
            }
            else {
                emailError.innerText = "";
            }
        });
    </script>
</body>
</html>

Real-Time Form Interaction & Events

JavaScript allows you to create dynamic and interactive forms by listening to various events such as input, change, and keyup.

Listening to input, change, and keyup Events

  1. input - Triggered when the value of an element is changed.
  2. change - Triggered when the value of an element has been committed.
  3. keyup - Triggered when a key is released.

HTML Code

<input type="text" id="myInput" name="myInput">

JavaScript Code

let inputField = document.querySelector("#myInput");

inputField.addEventListener("input", function() {
    console.log("Input event:", this.value);
});

inputField.addEventListener("change", function() {
    console.log("Change event:", this.value);
});

inputField.addEventListener("keyup", function() {
    console.log("Keyup event:", this.value);
});

Auto-Updating Content as Users Type

You can use these events to update content in real-time as users type in the form.

HTML Code

<textarea id="message" name="message" rows="4" cols="50"></textarea><br>
Character Count: <span id="charCount">0</span>

JavaScript Code

document.querySelector("#message").addEventListener("input", function() {
    document.querySelector("#charCount").innerText = this.value.length;
});

Example: Live Character Count

This example demonstrates how to display a live character count for a textarea.

<!DOCTYPE html>
<html>
<head>
    <title>Live Character Count</title>
</head>
<body>
    <label for="message">Enter your message:</label><br>
    <textarea id="message" name="message" rows="4" cols="50"></textarea><br>
    Character Count: <span id="charCount">0</span>

    <script>
        document.querySelector("#message").addEventListener("input", function() {
            document.querySelector("#charCount").innerText = this.value.length;
        });
    </script>
</body>
</html>