JavaScript Coder

How to keep checkbox values after form is submitted in Javascript

javascript checkbox checked form submit javascript form javascript check box

When working with forms in web applications, it’s common to encounter a situation where you want to retain the user’s selected checkbox values even after the form has been submitted. This tutorial will guide you on how to keep the checkbox value after a form submit in JavaScript. We’ll be using localStorage to store the selected checkbox values and retrieve them when the page is reloaded.

First, let’s create a simple HTML form with a few checkboxes:

<form id="myForm">
    <label>
        <input type="checkbox" name="option" value="option1"> Option 1
    </label>
    <label>
        <input type="checkbox" name="option" value="option2"> Option 2
    </label>
    <label>
        <input type="checkbox" name="option" value="option3"> Option 3
    </label>
    <button type="submit">Submit</button>
</form>

To prevent the page from reloading when the form is submitted, we’ll add an event listener to the form and call the preventDefault() method:

document.getElementById('myForm').addEventListener('submit', function (event) {
    event.preventDefault();
    // Remaining code will be added here
});

Save Checkbox Values to localStorage

Now we need to save the checked values to localStorage when the form is submitted:

function saveCheckboxValues() {
    const checkboxes = document.querySelectorAll('input[type="checkbox"]');
    let checkedValues = [];

    checkboxes.forEach(function (checkbox) {
        if (checkbox.checked) {
            checkedValues.push(checkbox.value);
        }
    });

    localStorage.setItem('checkedValues', JSON.stringify(checkedValues));
}

document.getElementById('myForm').addEventListener('submit', function (event) {
    event.preventDefault();
    saveCheckboxValues();
});

When the page is loaded back again we have to set the check box values back

Load Checkbox Values from localStorage

To load the saved checkbox values from localStorage, create a function called loadCheckboxValues() and call it when the page loads:

function loadCheckboxValues() {
    const checkedValues = JSON.parse(localStorage.getItem('checkedValues'));

    if (checkedValues) {
        const checkboxes = document.querySelectorAll('input[type="checkbox"]');
        checkboxes.forEach(function (checkbox) {
            if (checkedValues.includes(checkbox.value)) {
                checkbox.checked = true;
            }
        });
    }
}

loadCheckboxValues();

document.getElementById('myForm').addEventListener('submit', function (event) {
    event.preventDefault();
    saveCheckboxValues();
});

See Also