TypeScript: Handling HTML form onsubmit event

Updated: January 8, 2024 By: Guest Contributor Post a comment

Introduction

TypeScript enhances JavaScript by adding types and providing better tooling at any scale. When it comes to handling forms in the DOM, TypeScript can offer a more structured and error-resistant way to deal with the onsubmit event. In this tutorial, you will learn how to handle HTML form submission gracefully using TypeScript, with a step-by-step guide from basic usage to more sophisticated patterns.

Getting Started

Before diving into handling an onsubmit event, make sure you have a basic TypeScript environment ready. For this tutorial, we will use a simple TypeScript setup in an HTML page.

<!DOCTYPE html>
<html>
<head>
    <title>TypeScript Form Submission</title>
</head>
<body>
    <form id="example-form">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username">
        <input type="submit" value="Submit">
    </form>
    <script src="example.js"></script>
</body>
</html>

Next, you’ll need a TypeScript file, for this example it will be example.ts, which will be compiled to example.js.

Basic Form Submission in TypeScript

To handle form submissions, start by attaching an onsubmit event listener to your form. Here’s how you might set this up in TypeScript:

document.addEventListener('DOMContentLoaded', () => {
    const form = document.getElementById('example-form') as HTMLFormElement;
    form.onsubmit = (event) => {
        event.preventDefault();
        const formData = new FormData(form);
        const username = formData.get('username');
        console.log(`Username: ${username}`);
        // Perform further processing
    };
});

Type Safety with Interfaces

An advantage of TypeScript is the ability to define interfaces for form data, offering stronger contracts for your code.

interface UserForm {
    username: string;
}

document.addEventListener('DOMContentLoaded', () => {
    const form = document.getElementById('example-form') as HTMLFormElement;
    form.onsubmit = (event) => {
        event.preventDefault();
        const formData = new FormData(form);
        const user: UserForm = {
            username: formData.get('username') as string
        };
        console.log(user);
        // Further processing with type-safe user object
    };
});

Advanced Patterns: Generic Form Handler

For a more scalable solution, consider creating a generic form handler. This function can handle multiple forms with type safety.

function handleFormSubmit<T>(formElement: HTMLFormElement, dataHandler: (data: T) => void): void {
    formElement.onsubmit = (event) => {
        event.preventDefault();
        const formData = new FormData(formElement);
        const data = Object.fromEntries(formData.entries()) as T;
        dataHandler(data);
    };
}

document.addEventListener('DOMContentLoaded', () => {
    const form = document.getElementById('example-form') as HTMLFormElement;
    handleFormSubmit<UserForm>(form, (data) => {
        console.log(data);
       // Custom processing for UserForm data
    });
});

Conclusion

In this tutorial, you’ve seen how TypeScript can be used to handle HTML form onsubmit events in a type-safe and scalable way. By starting with basic setups and gradually delving into more advanced patterns, it’s clear that TypeScript brings value to DOM manipulation and event handling. Harnessing the power of type safety and modular code can lead to more maintainable and less error-prone applications.