Is it possible to save form forms in localStorage with pure Javascript? [duplicate]

1

I'm a beginner in Javascript and I'm making an application prototype for a college job, and I did not want to use a database or anything, because it's not worth it, I just need to test the GUI.

In my application, I have a form, and would like to save it to the localStorage.

But I need to save the form so that its fields are bound to the Local Storage form. As if it were a Json object with its attributes. (I do not know how to save on Json either.)

I imagined something like this:

<form onsubmit="return guardaFormulario();">
        <div>
            <label for="nome"> Nome: </label>
            <input type="text" id="nome" />
        </div>
        <div>
            <label for="agencia"> Agência: </label>
            <input type="text" id="agencia" />
        </div>

        <div class="button">
            <button type="submit">Enviar sua mensagem</button>
        </div>

    </form>

And the function triggered when submitting the form:

function guardaFormulario(){

   /*De alguma forma que eu não sei
 Guardo o formulário com seus atributos no local Storage */

}
    
asked by anonymous 22.04.2018 / 18:29

2 answers

2

The localStorage is very simple to use you use setItem() to store:

localStorage.setItem("chave", "valor");
//Ou
localStorage.chave = "valor";

And getItem() to retrieve this value:

localStorage.getItem("chave");
//Ou
localStorage.chave;

In W3School has a few more examples

An example usage:

<form>
  <input type='text' id='chave'>
  <input type='button' id='salvar' value='Salvar'>
</form>

<p id='mostrar'></p>

<script>    
    var entrada = document.getElementById('chave');

    var paragrafo = document.getElementById('mostrar');

    document.getElementById('salvar').addEventListener('click', function() {
      localStorage.chave = entrada.value;

      mostrar.innerText = localStorage.chave;
    });
</script>

To save a JSON object use stringfy() and parse() :

localStorage.chave = JSON.stringfy({subchave1 = "valor1", subchave2: true});

var objeto = JSON.parse(localStorage.chave);
console.log(objeto.subchave1);
    
22.04.2018 / 18:59
1

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;
         }

      }

   }
});
    
22.04.2018 / 21:40