Save Long Form Answers in the Browser
Keeps what visitors type into a long form saved in their browser, so a reload, a crash or an accidental back click does not wipe out their answers. Cleared after submitting.
Opens WPIDE on
Code
(function () {
var forms = document.querySelectorAll('form.wpide-save-progress, .wpide-save-progress form');
if (!forms.length || !window.localStorage) {
return;
}
forms.forEach(function (form, index) {
var key = 'wpideForm:' + location.pathname + ':' + (form.id || index);
var stored = {};
try { stored = JSON.parse(localStorage.getItem(key) || '{}'); } catch (e) { stored = {}; }
var fields = form.querySelectorAll('input:not([type="password"]):not([type="file"]):not([type="hidden"]):not([type="submit"]), textarea, select');
fields.forEach(function (field) {
if (!field.name || !(field.name in stored)) { return; }
if (field.type === 'checkbox' || field.type === 'radio') {
field.checked = stored[field.name].indexOf(field.value) !== -1;
} else if (!field.value) {
field.value = stored[field.name];
}
});
var save = function () {
var data = {};
fields.forEach(function (field) {
if (!field.name) { return; }
if (field.type === 'checkbox' || field.type === 'radio') {
data[field.name] = data[field.name] || [];
if (field.checked) { data[field.name].push(field.value); }
} else {
data[field.name] = field.value;
}
});
try { localStorage.setItem(key, JSON.stringify(data)); } catch (e) {}
};
var timer;
form.addEventListener('input', function () { clearTimeout(timer); timer = setTimeout(save, 400); });
form.addEventListener('change', save);
form.addEventListener('submit', function () { try { localStorage.removeItem(key); } catch (e) {} });
});
})();
Notes
Add the class wpide-save-progress to a form (most form builders have a CSS class setting); password, file and hidden fields are never stored.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.