-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
60 lines (48 loc) · 1.75 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
const expenseForm = document.getElementById("expense-form");
const expenseTableBody = document.querySelector("#expense-table tbody");
const totalExpenseDisplay = document.getElementById("total-expense");
let expenses = JSON.parse(localStorage.getItem("expenses")) || [];
// Add Expense
expenseForm.addEventListener("submit", (e) => {
e.preventDefault();
const name = document.getElementById("expense-name").value;
const amount = parseFloat(document.getElementById("expense-amount").value);
const category = document.getElementById("expense-category").value;
const expense = { name, amount, category, id: Date.now() };
expenses.push(expense);
updateUI();
saveToLocalStorage();
expenseForm.reset();
});
// Update UI
function updateUI() {
expenseTableBody.innerHTML = "";
let totalExpense = 0;
expenses.forEach((expense) => {
const row = document.createElement("tr");
row.innerHTML = `
<td>${expense.name}</td>
<td>$${expense.amount.toFixed(2)}</td>
<td>${expense.category}</td>
<td><button class="delete-btn" data-id="${expense.id}">Delete</button></td>
`;
expenseTableBody.appendChild(row);
totalExpense += expense.amount;
});
totalExpenseDisplay.textContent = `Total: $${totalExpense.toFixed(2)}`;
}
// Delete Expense
expenseTableBody.addEventListener("click", (e) => {
if (e.target.classList.contains("delete-btn")) {
const id = e.target.getAttribute("data-id");
expenses = expenses.filter((expense) => expense.id !== parseInt(id));
updateUI();
saveToLocalStorage();
}
});
// Save to Local Storage
function saveToLocalStorage() {
localStorage.setItem("expenses", JSON.stringify(expenses));
}
// Initialize UI
updateUI();