How to save Javascript objects in JSON format in localStorage, and then deserialize them?

Asked

Viewed 655 times

1

I am getting values from a form in html, then I want to use a function to take these values and create an object, making them attributes of this object.

Then, I want to store this object in the browser’s localStorage, in Json format, so I can get it back later...

Follow what I’ve done so far:

<div id="formulario" style="display:none">
   <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>
         <label for="conta"> Conta: </label>
         <input type="text" id="conta" />
      </div>
      <div class="button">
         <button type="submit">Localizar conta de cliente</button>
      </div>
   </form>
</div>
<script>
   function guardaFormulario(){
    var contaCliente = new Object();
    contaCliente.nome = getElementById('nome');
    contaCliente.agencia = getElementById('agencia');
    contaCliente.conta = getElementById('conta');

    //Aqui eu salvo o objeto no localStorage, como um objeto Json
   }

</script>

2 answers

4


Nothing like a test to know what’s going on (with some fixes):

  • getElementById() won’t work if you don’t use document before
  • Withdraw the display: none to see the form
  • Instead of putting a onsubmit="" on the form, put a onclick="" button and set it to type button not to reload the page

Code:

function guardaFormulario() {
    //Primeiro como você está fazendo (com as correções):
    var contaCliente = new Object();
    contaCliente.nome = document.getElementById('nome');
    contaCliente.agencia = document.getElementById('agencia');
    contaCliente.conta = document.getElementById('conta');

    console.log(contaCliente.valueOf());

    //Agora como eu acredito que você queira fazer:
    var contaCliente = new Object();
    contaCliente.nome = document.getElementById('nome').value;
    contaCliente.agencia = document.getElementById('agencia').value;
    contaCliente.conta = document.getElementById('conta').value;

    console.log(contaCliente.valueOf());
  }

<div id="formulario">

  <form>
    <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>
      <label for="conta"> Conta: </label>
      <input type="text" id="conta" />
    </div>

    <div class="button">
      <button onclick="guardaFormulario();" type="button">Localizar conta de cliente</button>
    </div>
  </form>
</div>

In the first console output an object with html elements will appear, and in the second an object with the input values of the form

But still this code can be simplified (as I would and with localStorage):

<div id="formulario">

  <form>
    <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>
      <label for="conta"> Conta: </label>
      <input type="text" id="conta" />
    </div>

    <div class="button">
      <button id="enviar" type="button">Localizar conta de cliente</button>
    </div>
  </form>
</div>
<script>
  //Variáveis dos inputs (html, sem o .value)
  var nome = document.getElementById('nome');
  var agencia = document.getElementById('agencia');
  var conta = document.getElementById('conta');
  //Variável do objeto que será guardado
  var obj;

  //Adiciona um ouvinte de evento ao botão para quando o usuário clicar nele
  document.getElementById('enviar').addEventListener('click', function() {
    //Monta o objeto que será salvo
    obj = {
      nome: nome.value,
      agencia: agencia.value,
      conta: conta.value
    };

    //Mostra no console o objeto antes de ser salvo no localStorage
    console.log(obj.valueOf());

    //Salva o objeto no localStorage
    localStorage[nome.value] = JSON.stringify(obj);

    //Mostra no console o objeto salvo
    console.log(JSON.parse(localStorage[nome.value]).valueOf());
  });
</script>
  • 1

    I wouldn’t change the event of form.submit to the button.click, because there are other ways to send a form without using a Submit button. One of them is to enter the last one input[text] form. For this reason I always use the event form.submit and use event.preventDefault();.

  • PS: Not wrong the answer, just wanted to add information that can help in decision making of someone who read the comments. :D

  • @fernandosavio me too :), but not to complicate left so

3

wrong

getElementById('nome')

correct

document.getElementById('nome').value

Script

function guardaFormulario(){

    nome = document.getElementById('nome').value;
    agencia = document.getElementById('agencia').value;
    conta = document.getElementById('conta').value;

    var testObject = { 'nome': nome, 'agencia': agencia, 'conta': conta };

     // Coloca o objeto no  storage
    localStorage.setItem('dadosBancarios', JSON.stringify(testObject));

    // Recupera o objeto do storage
    var retrievedObject = localStorage.getItem('dadosBancarios');

    console.log(retrievedObject);                  

}

to see the form you have to remove display: none

HTML

<div id="formulario">

        <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>
                <label for="conta"> Conta: </label>
                <input type="text" id="conta" />
            </div>

            <div class="button">
                <button type="submit">Localizar conta de cliente</button>
            </div>

        </form>

</div>
  • I’ll test your option here Leo. Thanks

  • Dude, I did it that way, but the content of the variables is not saved. The result that appears is: {name: {0: {}, 1: {}}, agencia: {}, conta: {}} agencia : {} conta : {} name : {0: {}, 1: {}}

  • @Lucaspletsch Tested my example I put in the first line of the answer? worked?

  • Yours worked. But your code didn’t work in my application. I’ve already solved it,.

Browser other questions tagged

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