-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
100 lines (75 loc) · 2.67 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
const btn = document.getElementById('btn-add')
let transactions = []
window.onload = () => {
const transactionsStored = JSON.parse(localStorage.getItem('transactions'))
if (transactionsStored != null) {
transactions = transactionsStored
}
loadHTML()
}
function loadHTML() {
//updating the total amount
const amount = document.getElementById('amount')
let totalAmount = 0
transactions.forEach(transaction => totalAmount += transaction.value)
if (totalAmount >= 0) {
amount.classList.add('positive')
amount.classList.remove('negative')
} else {
amount.classList.add('negative')
amount.classList.remove('positive')
}
amount.innerHTML = `R$ ${totalAmount.toFixed(2).replace('.', ',')}`
//creating the historic cards
const historic = document.getElementById('historic')
historic.innerHTML = '' //delete all the historic after, cuz if not the historic cards will repeat
transactions.forEach((transaction, index) => {
historic.innerHTML += `
<div class='historic-box'>
<button class='remove' onclick='removeItem(${index})'>X</button>
<h2 class='name'>${transaction.name.toLowerCase()}</h2>
<h2 class='value'>R$ ${transaction.value}</h2>
</div>`
}
)
}
function removeItem(index) {
transactions.splice(index, 1)
const transactionsFormated = JSON.stringify(transactions)
localStorage.setItem('transactions', transactionsFormated)
loadHTML()
}
function removeAll() {
transactions.splice(0, 99999999)
const transactionsFormated = JSON.stringify(transactions)
localStorage.setItem('transactions', transactionsFormated)
loadHTML()
}
function addToStorage(name, value) {
const transaction = {
name: name,
value: value
}
transactions.push(transaction)
const transactionsFormated = JSON.stringify(transactions)
localStorage.setItem('transactions', transactionsFormated)
loadHTML()
}
function getValues() {
const name = document.getElementById('name').value
let value = document.getElementById('value').value
value = parseFloat(value)
validateInputs(name, value)
document.getElementById('name').value = ''
document.getElementById('value').value = ''
}
function validateInputs(name, value) {
let popup = document.querySelector('.alert-error')
if (!isNaN(value) && name != '') {
popup.style.display = 'none'
addToStorage(name, value)
} else {
popup.style.display = 'flex'
}
}
btn.addEventListener('click', getValues)