Estou montando um sistema bem simples que faz contagens simples. Eu preciso que esses valores continuem escritos no HTML após a página ser recarregada, só não aprendi ainda como manipular o API do localStorage.
Aqui uma versão de exemplo autoexplicativa e simplificada executável da estrutura do meu código:
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>
Como podem ver, eu tenho 3 valores diferentes que serão somados no saldo 1 ou saldo 2, que são exibidos no HTML. Cada saldo também é somado entre si e o total também é exibido no HTML. Agora preciso que os valores não se percam quando a página for reiniciada, sendo possível continuar a fazer os cálculos partir de como estava anteriormente.
Podem me ajudar? Desde já, sou grata!
O código no jsFiddle: https://jsfiddle.net/m89awdoL/