localStorage save some fields

Asked

Viewed 620 times

2

Speak guys, I have a problem, as I use "localStorage" to save some fields of my form.

<script>    
    var entrada = document.getElementById('rua');
    var entrada2 = document.getElementById('bairro');

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

    document.getElementById('salvar').addEventListener('click', function() {

      localStorage.rua = entrada.value;
      localStorage.bairro = entrada2.value;


      mostrar.innerText += localStorage.rua;
      mostrar.innerText += localStorage.bairro;
    });
</script>
<form>
  <input type='text' id='rua'>
  <input type='text' id='bairro'>
  <input type='button' id='salvar' value='Salvar'>
</form>

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

Like that

  • In less than 5 minutes on Google you get your answer.

  • I would suggest that you revise the text of the question. You are confused to understand. What would this "Solution:"?

  • this solution would be a field of how user solved the problem, I did not enter much into the detail of the solution field why the filling of this field changes

2 answers

2


You do not need to create a Torage locale for each field. Just create an array of objects where each object in the array will have keys with the information, something like:

[
   {"rua": "rua 1", "bairro": "bairro A"},
   {"rua": "rua 2", "bairro": "bairro B"}
]

But since localStorage only saves information in string form, you will have to use JSON.stringify() to convert the array to string.

Below is an example of how you would do this (explanatory comments in the code):

var entrada = document.getElementById('rua');
var entrada2 = document.getElementById('bairro');
var paragrafo = document.getElementById('mostrar');

document.getElementById('salvar').addEventListener('click', function(){
   // cria um objeto com os valores dos campos
   var dados = { "rua": entrada.value, "bairro": entrada2.value };
   // puxa o localStorage para uma variável
   var ls = localStorage.getItem("infos");

   // verifica se o localStorage já existe
   if(ls){
      // converte o localStorage em array
      var json = JSON.parse(ls);
      // adiciona o objeto à array
      json.push(dados);
      // converte a array em string para salvar no localStorage
      json = JSON.stringify(json);
      // sobrescreve o localStorage com novos valores
      localStorage.setItem("infos", json);
   }else{
      // se não existe, cria com uma array convertida em string com os dados
      localStorage.setItem("infos", JSON.stringify([dados]));
   }

   // puxa novamente o localStorage atualizado em forma de array
   var ls_array = JSON.parse(localStorage.getItem("infos"));

   // cria uma string vazia
   var texto = '';

   // percorre a array do localStorage e alimenta a string vazia "texto"
   for(var item of ls_array){
      texto += "Rua: "+ item.rua +"<br>Bairro: "+ item.bairro +"<br><br>";
   }

   // insere o HTML em "texto" no <p>
   paragrafo.innerHTML = texto;

});

0

var nome = "João";

// insere o valor da variável "nome" no localStorage
localStorage.setItem("nome", nome);

// printa o valor da varável "nome" direto do localStorage
console.log(localStorage.getItem("nome"));

Browser other questions tagged

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