How do I store these values in the Torage locale?

Asked

Viewed 152 times

1

I’m putting together a very simple system that makes simple counts. I need these values to remain written in HTML after the page is reloaded, I just haven’t learned yet how to manipulate the localStorage API.

Here a simplified self-explanatory example version of my code structure executable:

    var total = window.document.getElementById('total')
    var debit = window.document.getElementById('debit')
    var credit = window.document.getElementById('credit')
    var somatotal = 0
    var somadebit = 0
    var somacredit = 0

    var valX = window.document.getElementById('valX')
    var valY = window.document.getElementById('valY')
    var valZ = window.document.getElementById('valZ')
    var somavalX = 0
    var somavalY = 0
    var somavalZ = 0

function addX() {
    var txtval = window.document.getElementById('txt-valX')
    var val = Number(txtval.value)
    var totalres = somatotal += val
    var totalval = somacredit += val
    total.innerText = totalres.toFixed(2)
    credit.innerText = totalval.toFixed(2)
    var valWay = somavalX += val
    valX.innerText = valWay.toFixed(2)
}
function addY() {
    var txtval = window.document.getElementById('txt-valY')
    var val = Number(txtval.value)
    var totalres = somatotal += val
    var totalval = somadebit += val
    total.innerText = totalres.toFixed(2)
    debit.innerText = totalval.toFixed(2)
    var valWay = somavalY += val
    valY.innerText = valWay.toFixed(2)
}
function addZ() {
    var txtval = window.document.getElementById('txt-valZ')
    var val = Number(txtval.value)
    var totalres = somatotal += val
    var totalval = somadebit += val
    total.innerText = totalres.toFixed(2)
    debit.innerText = totalval.toFixed(2)
    var valWay = somaY += val
    valY.innerText = valWay.toFixed(2)
}
Saldo 1:<div id="debit">0.00</div>
Saldo 2<div id="credit">0.00</div>
TOTAL:<div id="total">0.00</div>
<br><br>

Valor X:<div id="valX">0.00</div>
<input type="number" id="txt-valX" placeholder="vai add ao saldo 2">
<button onclick="addX()" id="bt0">OK</button><br>
Valor Y:<div id="valY">0.00</div>
<input type="number" id="txt-valY" placeholder="vai add ao saldo 1">
<button onclick="addY()" id="bt1">OK</button><br>
Valor Z:<div id="valZ">0.00</div>
<input type="number" id="txt-valZ" placeholder="vai add ao saldo 1">
<button onclick="addZ()" id="bt1">OK</button>

As you can see, I have 3 different values that will be summed in balance 1 or balance 2, which are displayed in HTML. Each balance is also added together and the total is also displayed in HTML. Now I need the values not to be lost when the page is restarted, being possible to continue the calculations from as it was before.

Can you help me? From now on, I’m grateful!

The code in jsFiddle: https://jsfiddle.net/m89awdoL/

2 answers

2


Augusto’s answer is already very explanatory.

Briefly, you use the localStorage.setItem(chave, valor) to save in the Torage. And uses the localStorage.getItem(chave) to recover from Storage.

Note the fact that when you recover this value, it will come as a string, so you will need to parse, as you have already done: var valorRecuperado = Number(localStorage.getItem(chave))

In your case, use the .setItem() at the end of each method executed to keep the value updated, and .getItem() at the beginning of your project to retrieve and add them in the text and input fields, using the properties .innerHTML and .value, respectively.

Official Mozilla reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/Window.localStorage

Hug

  • Hi, Diogo! Thanks for the answer. I’ve tried a lot, I’ve read a lot of sites, I’ve seen a lot of examples, but I didn’t get the expected result because I’ve noticed that it’s not enough to just store what’s in the div, but that the current value of the variables also has to be, in some way, stored so that the calculations are possible from that last value, you know? This already seems impossible for me to manage alone. If you could help me it would be too good! You can check the fiddle I left in the question and see if this is even possible?

  • Hi, Tamara! Q nice to see you starting with JS. I’m sure that soon you will be wild. I made some adjustments in your example, take a look: https://jsfiddle.net/diogocosta/uoL1k0s8/20/ Your code was very confusing, rs, but it is normal at first. So I’ve kind of changed a lot. Try to understand the nuances of the changes, to learn as much as you can. I hope you could have helped. Any questions, just drip. If it’s last for you, can you mark my answer as valid? A hug.

  • 1

    I decided to face Javascript recently hahaha was always running away from it, I’m still finding it extremely complicated, mainly logic, but I will not give up. I will make the most of your example by working! Thank you so much for dedicating your time to helping me in this! :D

  • that’s it! Count on me, for your commitment I saw that it has worked, hauhaha

1

Use the localStorage no mystery, it becomes available through the property Window.localStorage referencing an object of the type Storage that provides some methods and properties among them I highlight getItem() method that returns the value of a stored key, setItem() machine that adds or updates a certain key with the past value and property length which returns the number of stored items.

//Quando o DOM do documento inicial estiver completamente carregado e analisado
document.addEventListener("DOMContentLoaded", () => {

  //Cria uma referência para localStorage
  let storage = window.localStorage; 

  //Cria referência para os inputs
  let x = document.getElementById("x");
  let y = document.getElementById("y");
  let z = document.getElementById("z");

  //Verifica se existem itens armazenados no localStorage
  if (storage.length) {
    //Se tiver itens armazenados pega seus valores e atribui aos respectivos inputs
    x.value = storage.getItem("x"); 
    y.value = storage.getItem("y");
    z.value = storage.getItem("z");
  }

  //Instala eventos change para cada input referenciado nesse exemplo

  x.addEventListener("change", () => {
    //Caso input x tenha sido alterado armazena o novo valor no localStorage sob a chave x
    storage.setItem("x", x.value); 
  });

  y.addEventListener("change", () => {
    //Caso input y tenha sido alterado armazena o novo valor no localStorage sob a chave y
    storage.setItem("y", y.value);
  });

  z.addEventListener("change", () => {
    //Caso input z tenha sido alterado armazena o novo valor no localStorage sob a chave z
    storage.setItem("z", z.value);
  });

})
input {
  display: block;
}
<label>Valor X:<input type="number" id="x"></label>
<label>Valor Y:<input type="number" id="y"></label>
<label>Valor Z:<input type="number" id="z"></label>

See this example working on Repli.it: https://repl.it/repls/FamiliarWarmAutomaticparallelization

I did not provide the execute button on the page because here the code rotates in a sandbox where the localStorage is disabled by account of the directive Same-origin policy. To see the code working use the link above.

  • Augusto, thank you very much for your answer! Look, I don’t know if it’s because I’m too beginner or if my Qi is low for logic (rs), but I can’t understand, I’ve tried a lot here. I started JS 1 month ago but I’m pretty lost yet. Would it be possible for you to edit in my jsFiddle version? It would help me understand better by observing how it works in practice.

  • i tried so, see: https://jsfiddle.net/89feyh6w/1/

Browser other questions tagged

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