With localStorage
you can store the data of a form in JSON string format.
Using
FormData
you store all form elements in an object, then making a
for
you add the entries in an object, it will be in this format, the name = > value :
{"nome":"fulano","email":"[email protected]" ... }
To retrieve the data, you use JSON.parse
to convert the data saved in localStorage
to JSON object and use for
to populate the form with saved values.
In this for
you search the form elements for their name
and enter their value. But you must also check the type ( type
) of the elements, because some will receive value
( input
, select
, button
, textarea
...) and other checked
( radio
and checkbox
).
I've written the code below that will do all of this.
In this link you can test on a basic form.
Code:
// pega o click do botão de submit do formulário
document.body.querySelector("button").addEventListener("click", function(){
var form = document.body.querySelector("form"),
data = new FormData(form),
json = {}; // objeto que irá guardar os dados
for(var dados of form){
var typ = document.body.querySelector("[name='"+dados.name+"']").type,
val = dados.value;
if(typ == "radio"){
val = document.body.querySelector("[name='"+dados.name+"']:checked").value;
}else if(typ == "checkbox"){
val = document.body.querySelector("[name='"+dados.name+"']").checked;
}else if(typ == "select-multiple"){
var mul = [],
els = document.body.querySelector("[name='"+dados.name+"']").options;
for(var x=0; x<els.length; x++){
if(els[x].selected){
mul.push(els[x].value);
}
}
val = mul;
}
json[dados.name] = val;
}
localStorage.setItem("formulario", JSON.stringify(json));
});
// recuperação dos dados guardados no localStorage
document.addEventListener("DOMContentLoaded", function(){
var formulario = localStorage.getItem("formulario");
if(formulario){ // verifico se o localStorage existe
var form = document.body.querySelector("form");
formulario = JSON.parse(formulario);
for(var dados in formulario){
var tag = document.body.querySelector("[name='"+dados+"']").tagName,
typ = document.body.querySelector("[name='"+dados+"']").type;
if(tag.match(/INPUT|SELECT|TEXTAREA/) && !typ.match(/radio|checkbox|select-multiple/)){
document.body.querySelector("[name='"+dados+"']").value = formulario[dados];
}else if(typ == "checkbox"){
document.body.querySelector("[name='"+dados+"']").checked = formulario[dados];
}else if(typ == "select-multiple"){
var mul = formulario[dados];
for(var item of mul){
document.body.querySelector("[name='"+dados+"'] option[value='"+item+"']").selected = true;
}
}else if(typ == "radio"){
document.body.querySelector("[name='"+dados+"'][value='"+formulario[dados]+"']").checked = true;
}
}
}
});