JavaScript Coder

How to Store Multiple Form Data in LocalStorage Using JavaScript

javascript form localstorage javascript form

LocalStorage allows you to store data on the client-side, which persists even after the browser is closed. In this tutorial, we’ll walk through the process of storing multiple form data in LocalStorage using JavaScript.

First, create an HTML file with a form containing some input fields. For this example, let’s create a simple registration form.

<form id="registrationForm">
        <label for="fullName">Full Name:</label>
        <input type="text" id="fullName" name="fullName" required>

        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required>

        <label for="password">Password:</label>
        <input type="password" id="password" name="password" required>

        <button type="submit">Register</button>
    </form>

JavaScript code for storing form data

document.getElementById('registrationForm').addEventListener('submit', function(event) {
    event.preventDefault();

    const fullName = document.getElementById('fullName').value;
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;

    const formData = {
        fullName: fullName,
        email: email,
        password: password
    };

    saveFormData(formData);
});

function saveFormData(formData) {
    const storedFormData = JSON.parse(localStorage.getItem('formData')) || [];

    storedFormData.push(formData);

    localStorage.setItem('formData', JSON.stringify(storedFormData));
}

In this code, we add an event listener to the form’s submit event. When the form is submitted, we prevent the default behavior and collect the form data into an object. Then, we call the saveFormData() function, which retrieves any existing form data from LocalStorage, appends the new data, and stores it back in LocalStorage.

Open the HTML file in a web browser and test the form by submitting multiple entries. You can use the browser’s developer tools to inspect the LocalStorage data to ensure it is being saved correctly.

See Also