localStorage.getItem does not work

Asked

Viewed 250 times

-2

Good evening, could you help me? I’m trying to pass the data from one page to another but the field is empty. page 1: where I take the data. page 2: where I want to insert that data.

PAGE 1:

<h1 class="tituloProd">Arroz Tio João integral tipo 1 - 5KG</h1>

PAGE 2:

<p class="descricaoProduto">Descricao aqui<p> 

      $('#btnCompra').click (function(){
       localStorage.setItem('tituloProd', 'arroz');
       $('.descricaoProduto').text(localStorage.getItem('tituloProd'));
  });
});

FULL JAVASCRIPT:

$(document).ready(function(){
$('#btnCompra').click (function(){
  $('#modalProduto').modal('hide'); 
  $('#divInfo').css('display','block'); /* exibe uma div de alerta */
  var titulo = $('#tituloProd').text();
  localStorage.setItem("titulo_produto", titulo);
});

$('#carrinho').click (function(){
  $('#descricaoProduto').text(localStorage.getItem("titulo_produto"));
});
});

1 answer

2

So Weslley, by the code you posted, you’re setting and taking the value on the same page and not setting the value on page 1 and taking page 2, the right one would be:

Page 1

HTML - Página 1

<h1 id="tituloProd">Arroz Tio João integral tipo 1 - 5KG</h1>

JS - Página 1

//pega o texto
let titulo = $("#tituloProd").text();

// titulo_produto é a chave e titulo o valor que serão armazenados no localStorage   
localStorage.setItem("titulo_produto", titulo);

Page 2

HTML - Página 2

<p id="descricaoProduto"></p>

JS - Página 2

$("#btnCompra").click(function(){
  // Aqui obtém o valor através da chave
  $("#descricaoProduto").text(localStorage.getItem("titulo_produto"));
});

I also suggest changing classes by id to set and pick specific values on the page.

  • Good afternoon Leandrade! Thanks for the resolution, it worked! Now I have another problem. My goal was: when I clicked on the cart, the field was set in the product div, this worked, but the value appears for a short period of time and then disappears, IE, when I click on the cart, appears the field set and then disappears, Oce knows what can be?

  • Put the whole function to see, with the code you posted has no way of knowing.

  • Ready! I’ve entered the full function

  • Guy is very confused your code, but, by what posted not to see the pq is occurring this show behavior and then disappear, can be related to the ** $('#modalProduto'). modal('Hide');**, which is to hide the modal with id modalProduct.

  • 1

    Good evening Leandreade, I discovered the problem. My "btnCarrinho" was a link (<a>) and every time I clicked on it, the page updated. The reason the value disappeared did not understand, since localStorage remains after updates, but I removed the tag a and it worked all right.

Browser other questions tagged

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