jlelse’s Blog

Thoughts, stories and ideas

Simply cache form fields in localStorage

Published on in 👨‍💻 Dev
Short link: https://b.jlel.se/s/463
Share online Translate

Have you ever started typing something into a web form and then you accidentally closed the browser and lost everything you typed there? Because of that I usually use an external text editor for long posts and later copy the text into my blog editor.

But no more.

I found a simple solution, that requires less than 20 lines of JavaScript (including comments) — a legit of use of JS.

(function () {
    const fc = 'formcache'
    Array.from(document.querySelectorAll('form .' + fc)).forEach(element => {
        let elementName = fc + '-' + location.pathname + '#' + element.id
        // Load from cache
        let cached = localStorage.getItem(elementName)
        if (cached != null) {
            element.value = cached
        }
        // Auto save to cache
        element.addEventListener('input', function () {
            localStorage.setItem(elementName, element.value)
        })
        // Clear on submit
        element.form.addEventListener('submit', function () {
            localStorage.removeItem(elementName)
        })
    })
})()

This code, attached as a script with defer attribute, ensures that for all form inputs that use the formcache class (and have an id!), when text is entered, it is cached in localStorage and thus preserved when the tab or browser is closed.

When the page is opened, it checks if there is already a cached value and creates a listener so that the content is deleted when the form is submitted.

Simple.

Tags:

Jan-Lukas Else
Interactions & Comments