JSFiddle - React, Tailwind, and code Playground

by diogocosta

HTML

<h4> Cred: </h4>
<div id="credit">0.00</div>

<h4> Deb: </h4>
<div id="debit">0.00</div>

<h4> Total: </h4>
<div id="total">0.00</div>
<br /><br />

<div>
  <label>Valor Cred (X): <input type="number" id="x"></label>
  <button onclick="addCred()">OK</button>
</div>
<div>
  <label>Valor Deb (Y): <input type="number" id="y"></label>
  <button onclick="addDeb('y')">OK</button>
</div>
<div>
  <label>Valor Deb (Z): <input type="number" id="z"></label>
  <button onclick="addDeb('z')">OK</button>
</div>

CSS

*, html {
  font-family: Helvetica, Arial, sans-serif;
  font-size: 100%;
}
h4 {
  margin: 0;
  padding: 0;
}
div {
  margin-bottom: 5px;
}

JavaScript

var total = window.document.getElementById('total')
var debit = window.document.getElementById('debit')
var credit = window.document.getElementById('credit')    

var somacredit = recoverItemFromStorage('val_cred')
var somadebit = recoverItemFromStorage('val_deb')
var somatotal = recoverItemFromStorage('val_tot')

debit.innerHTML = somadebit.toFixed(2)
credit.innerHTML = somacredit.toFixed(2)
total.innerHTML = somatotal.toFixed(2)

function addCred() {
  var txtval = window.document.getElementById('x')
  var val = Number(txtval.value)
  var totalres = somatotal += val
  var totalCred = somacredit += val
  total.innerText = totalres.toFixed(2)
  credit.innerText = totalCred.toFixed(2)
  saveItemToStorage('val_cred', totalCred)
  saveItemToStorage('val_tot', totalres)
}
function addDeb(id) {
  var txtval = window.document.getElementById(id)
  var val = Number(txtval.value)
  var totalres = somatotal += val
  var totalDeb = somadebit += val
  total.innerText = totalres.toFixed(2)
  debit.innerText = totalDeb.toFixed(2)
  saveItemToStorage('val_deb', totalDeb)
  saveItemToStorage('val_tot', totalres)
}

function saveItemToStorage(key, value) {
	localStorage.setItem(key, value)
}

function recoverItemFromStorage(key) {
	return Number(localStorage.getItem(key))
}