Is it possible to save <form> forms in localStorage with pure Javascript?

Asked

Viewed 2,191 times

2

I’m a beginner in Javascript and I’m making a prototype application for a college job, and I didn’t want to use a database or anything, because it’s not worth it, I just need to test the functioning of the GUI.

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

But I need to save the form so that your fields are linked to the form lo local Storage. As if it were a Json object with its attributes. (I also can’t save in Json).

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 */

}
  • 1

    As it is a college job you can store a JSON object in string format in the Storage. Or if you want something like database search on SQL Web that modern browsers support.

  • 1

    Which part do you already know and which part do you doubt? Your question involves several questions, among them 3 fundamental: recover whole form data, serialize the data, persist in Storage location. It would be better to [Dit] the question and solve one step at a time, opening new questions to the next steps as you solve each.

  • @Bacco take a look now please?

  • See the reply at https://answall.com/questions/293265/comorsalvar-objetos-javascript-no-formato-json-na-localstorage-e-depois-desseri/293275#293275

2 answers

2

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

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

And the getItem() to recover this value:

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

In the W3school has a few more examples

An example of use:

<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);
  • Okay, but the question is how to save the form. For this, could I, instead of indicating a web page in the form’s "action", use a function call that saves it in localStorage? What would the code for that look like?

  • 1

    I edited the answer with one use. It is not necessary to submit the form, just add an event listener on a button for example, and save/search on localStorage

  • But that way you’re saving every field of the form yourself, right? I wanted, with a form, to save an "object" "account of a client", so that I could recover the data of that account by the name of the client, for example.

  • 1

    then you can do as @Thiagosilr commented, create an object and save it as string: joão: "{chave1: true, chave2: 15.3, ...}"

  • That, but like, I create a javascript object, and save it to localStorage from there? What does that look like?

  • 1

    I added the answer how to manipulate JSON objects

  • Can I use an attribute as a key, and the rest as sub-keys? Example: var name = getElementById('name'); var agencia = getElementById('agencia'); var account = getElementById('account'); localStorage.meuObject = JSON.stringfy(name= "name"{subchave1 = "agency", subchave2: "account"});

  • Let me ask you a specific question...

  • You want to save all form html with the values of your inputs?

  • Kind of. By filling out this form, I’m creating a client with your agency and account.

  • I asked a specific question regarding saving this form object as Json here: https://answall.com/questions/293265/como-salvar-objetos-javascript-no-formato-json-na-localstorage-e-depois-desseri

  • 1

    Something like localStorage.joao = {agencia: document.getElementById('agencia').value, conta: document.getElementById('conta').value}

  • Exactly! I’ll try

Show 8 more comments

1

With localStorage you can store the data of a form in JSON string format.

Using FormData you store all the form elements in an object, then making a for you add the entries in an object, will be in this format, being the pairs name => value:

{"nome":"fulano","email":"[email protected]" ... }

To recover the data, you use the JSON.parse to convert the data saved in localStorage in JSON object and use a for to populate the form with the values saved.

In that for you search the form elements by your name and enter its value. But you also need to check the type (type) of the elements, because some will receive value (input, select, button, textarea...) and others checked (radio and checkbox).

I wrote the code below that will do all this.

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

      }

   }
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.