Save items and recover values with Localstorage

Asked

Viewed 2,183 times

1

Good morning, everyone. I have a stroller where I record items for an estimate. Until then I can record this item in the cart in the localStorage and persist this data in this same item, the user can change page, close the browser and etc..

But when I add a second item to the cart I cannot keep each selection of each item, only the first.

Picture of inputs inserir a descrição da imagem aqui

Code js:

var saveItemCart = function(){
var cart = {
      cores: document.getElementById("cor_add").value,
      qtd_gomos: document.getElementById("qtd_gomos").value,
      qtd_cores: document.getElementById("qtd_cores").value,
      quantidade: document.getElementById("quantidade").value,
      obs: document.getElementById("obs").value, 
    };  
    localStorage.setItem('cart', JSON.stringify(cart));  
}

  document.onchange = saveItemCart;

  if(document.getElementById('id{{$row->id}}')){
  if (localStorage.cart) {
  document.getElementById('cor_add').value = JSON.parse(localStorage.getItem('cart')).cores;
  }
  if (localStorage.cart) {
  document.getElementById('qtd_gomos').value = JSON.parse(localStorage.getItem('cart')).qtd_gomos;
}
  if (localStorage.cart) {
  document.getElementById('qtd_cores').value = JSON.parse(localStorage.getItem('cart')).qtd_cores;
}
  if (localStorage.cart) {
  document.getElementById('quantidade').value = JSON.parse(localStorage.getItem('cart')).quantidade;
}
  if (localStorage.cart) {
  document.getElementById('obs').value = JSON.parse(localStorage.getItem('cart')).obs;
}}else( localStorage.clear());

Image of the Localstorage inserir a descrição da imagem aqui

How could you define for each item to have its values? If you need more information I edit the post.

Thank you.

  • Each entry in the Storage location must have a different name, if you call all of Cart will be overwritten, modify the value names of the Storage location and add as many objects as you want there.

  • Hi @Sabrinab. thanks for the reply. Overall JS would be right? I understood what you meant, I will try to put the ID that comes from each product.

  • I found no problems beyond the envelope I mentioned.

5 answers

1

This would not be the case to save an array instead of saving a single object to the localStorage?

var saveItemCart = function(){
  var cart = localStorage['cart'] ? JSON.parse(localStorage['cart']) : [];

  cart.push({
    cores: document.getElementById("cor_add").value,
    qtd_gomos: document.getElementById("qtd_gomos").value,
    qtd_cores: document.getElementById("qtd_cores").value,
    quantidade: document.getElementById("quantidade").value,
    obs: document.getElementById("obs").value, 
  });

  localStorage.setItem('cart', JSON.stringify(cart));  
}

A good idea would be to also record an identifier number on each item, so it is easy to remove an item from the cart when you need it, or even increase the amount of an item that already exists.

  • Hello, and how would I enter the variable inside each cart item? Document.getElementById('cor_add'). value = JSON.parse(localStorage.getItem('colors')[1]);

  • You have to make one for, but more importantly, you need to create the DOM elements dynamically, because I see in your code only one cart item will appear, although the cart has an undefined number of items.

  • Right, when you say dynamically create the DOM elements you mean the id’s I’m picking up? EX: cor_add_1 cor_add_2

  • Yes, that’s one way to do it, but what I meant is that you need to generate these elements with JS.

  • You could show me an example?

  • It would be better to open another question by posting your HTML and explaining the doubt itself.

Show 1 more comment

1

Taking content from Localstorage and playing an input:

let storageValue = JSON.parse(localStorage.getItem(myKey));
document.getElementById(myInput).value = storageValue;

If you have multiple values just take the results separately and follow this example

0

Hello. You can store items in JSON as a Jsons array. To add a new item, you can take all the other already added ones and store them in an array, push the new item in the array and store the array in localStorage.

var saveItemCart = function(){
    var item = {
         cores: document.getElementById("cor_add").value,
         qtd_gomos: document.getElementById("qtd_gomos").value,
         qtd_cores: document.getElementById("qtd_cores").value,
         quantidade: document.getElementById("quantidade").value,
         obs: document.getElementById("obs").value, 
    };
    cart = localStorage.getItem('cart');
    cart = JSON.parse(cart);
    cart.push(item);
    cart = JSON.stringify(cart);
    localStorage.setItem('cart', JSON.stringify(cart));

}

  • Hello Lucas, is this for more than one item too? For example I add an ID inside the items. ?

0

You can create a different key for each item and store it separately, or you can save a cart JSON within localStorage and retrieve it later.

Follow the JSON example:

var carrinho = [
{item1},
{item2},
...
];

localStorage.setItem("carrinho_key", JSON.stringify(carrinho));
  • Hello @Vinicius, that key I could create with a for()?

  • No need, when you get the key item you will already see all the json in the string, then you can break it using a for and distribute to your desired fields. the JSON.stringify(cart) code transforms your vector into a string so that it can be stored, it will look something like: '[{item1...}, {item2...}]', then you can transform it into a variable again by retrieving it from localStorage and converting it: obj = JSON.parse(local text Storage);

  • you could give an example with my code?

0

It turns out you have a small problem in the code, you should save the list of items in the cart (in array form) and update the item when necessary and update the list, and suggest that the items have id or sku so you can separate the items

  1. Modify the item object to have id, color, qtd_gums, qtd_colors, quantity, Obs

  2. Create a list to update (add, update, remove items) the Cart that is saved in localStorage

3.Create a function to save and fetch Cart and also a function to update the item(s) inside the list and put in the localstorage

// funcao para buscar itens no localStorage
var getCart = function() {
  return localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart')) : [];
}

//funcao para gravar itens no localStorage
var setCart = function(cartItems){
  localStorage.setItem('cart', JSON.stringify(cartItems)); 
}

//funcao para verificar se o item ja existe no cart 
var hasItem = function(item) {
  var cart = getCart();
  if(!item.id)
    return false
  return cart.some(cartItem => item.id == cartItem.id )
}

//funcao para gravar item
var saveItemCart = function(){
  item = {
      id: document.getElementById("sku").value,//ou pode ser gerado na hora usando size
      cores: document.getElementById("cor_add").value,
      qtd_gomos: document.getElementById("qtd_gomos").value,
      qtd_cores: document.getElementById("qtd_cores").value,
      quantidade: document.getElementById("quantidade").value,
      obs: document.getElementById("obs").value, 
    }  
    var cart = getCart()
    if(hasItem(item)) {
    //condicao para actualizar item caso ja tenha sido gravado
      cart.forEach(cartItem => {
        if(cartItem.id == item.id){
          cartItem.cores = item.cores
          cartItem.qtd_gomos = item.qtd_gomos
          cartItem.qtd_cores = item.qtd_cores
          cartItem.quantidade = item.quantidade
          cartItem.obs = item.obs
        }
      })
    }else{
    //condicao param criar id caso nao exista nenhum no sistema
    if(!item.id)
      item.id = cart.length + 1
    
     //condicao para adicionar item caso nao tenha no cart  
      cart.push(item)
    }
    
    //instrucao para actualizar o cart no localStorage
    setCart(cart)
}

with this you can already have the item list and if necessary update or even add items to the list

  • Hello Adelino, I will test, soon I answer if it worked.

  • Adelino, how do I play in inputs what is in Localstorage? Can you explain to me!

  • Sorry I’m not sure what you mean by play? Want to change the dice is that it? @adrib

  • All you have to do is take the data from getCart() and do a for in the inputs, if you want to have a more detailed answer on how to do this, ask another question and put your HTML so we can help you

Browser other questions tagged

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