← Tous les articles

Autosave long form drafts in JavaScript with localStorage

A tab closed by mistake or a dead battery, and a visitor loses twenty minutes of typing on your quote form. Saving a local draft takes a few lines of JavaScript, as long as you avoid a handful of traps.

Autosave long form drafts in JavaScript with localStorage

Key points

  • Save fields to localStorage a few hundred milliseconds after the last keystroke.
  • Never store passwords, files or sensitive data in the browser.
  • Clear the draft after a successful submission, not when the button is clicked.

Detailed quote requests, job applications and course sign-ups often take fifteen minutes to fill in. One accidental reload or stray link click wipes everything, and most people don’t start again. On our projects, local draft saving is one of those small upgrades clients actually notice, because their own leads mention it.

Save without slowing typing down

Listen for input on the whole form and wait for a short pause before writing, so you don’t serialise the form on every keystroke:

const form = document.querySelector('#quote-form');
const KEY = 'draft:quote-form:v1';
const SKIP = ['password', 'file', 'hidden', 'submit', 'button'];

function collect() {
  const data = {};
  for (const el of form.elements) {
    if (!el.name || SKIP.includes(el.type) || 'noDraft' in el.dataset) continue;
    if (el.type === 'checkbox' || el.type === 'radio') {
      data[el.name] ??= [];
      if (el.checked) data[el.name].push(el.value);
    } else {
      data[el.name] = el.value;
    }
  }
  return data;
}

function save() {
  try {
    localStorage.setItem(KEY, JSON.stringify({ savedAt: Date.now(), data: collect() }));
  } catch {
    // Storage full or blocked (private mode, settings): no draft, no crash
  }
}

let timer;
form.addEventListener('input', () => {
  clearTimeout(timer);
  timer = setTimeout(save, 400);
});

Checkboxes are stored as a list even when empty. Otherwise a box that was checked by default and then unchecked would come back checked on restore. The v1 suffix in the key pays off when the form changes: bump it to v2 and old drafts are ignored.

Restore, and tell the visitor

On load, read the draft back if it isn’t too old and fill the fields. Always say so, with a button to start over: a form that fills itself in without explanation is unsettling.

const MAX_AGE = 7 * 24 * 60 * 60 * 1000; // one week

function restore() {
  let draft = null;
  try {
    draft = JSON.parse(localStorage.getItem(KEY));
  } catch {
    return false;
  }
  if (!draft || Date.now() - draft.savedAt > MAX_AGE) return false;

  for (const el of form.elements) {
    if (!(el.name in draft.data)) continue;
    const value = draft.data[el.name];
    if (el.type === 'checkbox' || el.type === 'radio') {
      el.checked = value.includes(el.value);
    } else {
      el.value = value;
    }
  }
  return true;
}

function clearDraft() {
  try { localStorage.removeItem(KEY); } catch {}
}

if (restore()) {
  document.querySelector('#draft-notice').hidden = false;
}

If parts of the form appear depending on earlier answers, dispatch a change event on those fields after restoring so your show/hide logic catches up. Keep the notice short and place it right above the first field, where the visitor is already looking.

What not to store

Any script on the page can read localStorage, and the data stays on the device, shared computers included. Leave out passwords, card numbers, ID documents and health fields: adding data-no-draft to the field is enough with the code above. File inputs can’t be restored anyway.

For a particularly sensitive form, use sessionStorage: the draft survives a reload but disappears when the tab is closed.

Clear the draft at the right moment

The most common trap is clearing the draft on submit click. If the server rejects the submission (invalid field, expired session), the visitor lands back on an empty form. Call clearDraft() only once success is confirmed: in the fetch response handler, or on the thank-you page for a classic form post.

FAQ

Does this work with WordPress form plugins?

Yes, it works on any HTML form. Target the right selector and check that the plugin doesn’t re-render the form via AJAX after submission.

Do we need the visitor’s consent?

The draft never leaves their device, but it does hold personal data. A restore banner with a “Discard” button keeps them in control; check the details with whoever handles data protection on your side.

Is your quote form losing leads halfway through? We review and improve it, from usability to how the data is sent.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →