To address the issues you're encountering with the Expense Tracker application, let's ensure we have a clearer picture of how the expenses are being displayed and how the functionalities, especially for editing and exporting to CSV, are working.
Key Requirements for Displaying Expenses and Functioning Properly:
- Dynamic Rendering of Expenses: Each expense should correctly display its name, amount, category, and include buttons for editing.
- CSV Export Functionality: The exported CSV file should correctly reflect all the ongoing expenses.
- Clean UI for Editing and Deleting: The buttons for editing and deleting should function correctly without cluttering each expense line.
Let's optimize your code to ensure a clean output, including improving the display format and maintaining clarity. Here’s a concise review of the adjustments needed in your JavaScript and HTML, along with some CSS enhancements if required.
Final Implementation
1. HTML Code (index.html)
Ensure your HTML remains as provided earlier. Here’s a reminder of the structure, which is essential to maintain functionality.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Net Worth Expense Tracker</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>Expense Tracker</h1>
<div class="input-group">
<label for="totalIncome">Total Income:</label>
<input type="number" id="totalIncome" placeholder="Enter your income" min="0" required>
<button class="action-btn" id="totalIncomeBtn">Set Income</button>
</div>
<form id="expenseForm">
<div class="input-group">
<label for="expenseName">Expense Name:</label>
<input type="text" id="expenseName" placeholder="Enter expense name" required>
</div>
<div class="input-group">
<label for="expenseAmount">Expense Amount:</label>
<input type="number" id="expenseAmount" placeholder="Enter expense amount" min="0" required>
</div>
<div class="input-group">
<label for="expenseCategory">Category:</label>
<select id="expenseCategory" required>
<option value="Housing">Housing</option>
<option value="Utilities">Utilities</option>
<option value="Insurance">Insurance</option>
<option value="Groceries">Groceries</option>
<option value="Transportation">Transportation</option>
<option value="Healthcare">Healthcare</option>
<option value="Dining Out">Dining Out</option>
<option value="Entertainment">Entertainment</option>
<option value="Clothing">Clothing</option>
<option value="Debt">Debt</option>
<option value="Parenting">Parenting Expenses</option>
<option value="Savings">Savings</option>
</select>
</div>
<button type="submit" class="action-btn" id="submitExpenseBtn">Add Expense</button>
</form>
<div class="currency-group">
<label for="currencySelect">Currency:</label>
<select id="currencySelect">
<option value="USD">$ USD</option>
<option value="INR">₹ INR</option>
<option value="IDR">Rp IDR</option>
<option value="LKR">රු LKR</option>
<option value="AED">د.إ AED</option>
</select>
</div>
<div class="summary">
<p>Total Expenses: <span id="totalExpenses">0.00</span></p>
<p>Remaining Balance: <span id="remainingBalance">0.00</span></p>
</div>
<button id="toggleEditModeBtn" class="action-btn">Enable Edit Mode</button>
<button id="updateSelectedBtn" class="action-btn" style="display:none;">Update Selected</button>
<button id="toggleDeleteModeBtn" class="action-btn">Enable Delete Mode</button>
<button id="deleteSelectedBtn" class="action-btn" style="display:none;">Delete Selected</button>
<ul id="expenseList" class="expense-list"></ul>
<div class="buttons">
<button id="exportCsvBtn" class="action-btn">Export to CSV</button>
<button id="shareAppBtn" class="action-btn">Share App</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
2. CSS Code (style.css)
The CSS for visual enhancements:
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
margin: 0;
padding: 0;
}
.container {
max-width: 600px;
margin: 50px auto;
background: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
h1 {
text-align: center;
color: #333;
}
.input-group,
.currency-group,
.buttons {
margin-bottom: 15px;
}
label {
font-weight: bold;
margin-bottom: 5px;
}
input, select, button {
width: 100%; /* Make inputs fill the available width */
padding: 10px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
cursor: pointer;
}
.action-btn {
background-color: #28a745;
color: white;
border: none;
padding: 10px 15px;
margin-top: 10px;
font-size: 16px;
}
.action-btn:hover {
background-color: #218838;
}
.summary {
text-align: center;
margin-top: 20px;
}
.summary p {
font-size: 18px;
margin: 5px 0; /* Space between summary items */
}
.expense-list {
list-style-type: none;
padding: 0;
}
.expense-item {
display: flex;
justify-content: space-between;
padding: 10px;
background: #f9f9f9;
border-radius: 5px;
margin-bottom: 10px;
border: 1px solid #ddd;
}
.expense-item span {
flex: 1; /* Allow span to grow */
}
.expense-item input[type="checkbox"] {
margin-right: 10px;
}
@media (max-width: 768px) {
.container {
margin: 20px;
padding: 15px;
}
}
3. JavaScript Code (script.js)
Ensure the logic is tight for adding, editing, deleting, and exporting expenses correctly.
document.addEventListener("DOMContentLoaded", () => {
const form = document.getElementById("expenseForm");
const totalIncomeInput = document.getElementById("totalIncome");
const expenseList = document.getElementById("expenseList");
const totalExpenses = document.getElementById("totalExpenses");
const remainingBalance = document.getElementById("remainingBalance");
const currencySelect = document.getElementById("currencySelect");
let state = {
income: 0,
expenses: 0,
currency: currencySelect.value,
};
let editingExpenses = [];
let deleteMode = false;
let editMode = false;
const updateSummary = () => {
totalExpenses.textContent = `${state.currency} ${state.expenses.toFixed(2)}`;
remainingBalance.textContent = `${state.currency} ${(state.income - state.expenses).toFixed(2)}`;
};
const toSentenceCase = (str) => {
return str.toLowerCase().replace(/\b\w/g, char => char.toUpperCase());
};
const addExpenseToDOM = (name, amount, category) => {
const formattedName = toSentenceCase(name);
const formattedCategory = toSentenceCase(category);
const expenseItem = document.createElement("li");
expenseItem.classList.add("expense-item");
expenseItem.innerHTML = `
<input type="checkbox" class="expense-checkbox">
<span>${formattedName} (${formattedCategory})</span>
<span>${state.currency} ${amount.toFixed(2)}</span>
<button class="edit-btn">Edit</button>
`;
expenseList.appendChild(expenseItem);
expenseItem.querySelector(".edit-btn").addEventListener("click", () => {
if (!deleteMode) startEditingExpense(expenseItem);
});
};
const deleteSelectedExpenses = () => {
const checkboxes = document.querySelectorAll(".expense-checkbox");
checkboxes.forEach((checkbox) => {
if (checkbox.checked) {
const amount = parseFloat(checkbox.parentElement.nextElementSibling.textContent.split(" ")[1]);
state.expenses -= amount; // Update the total expenses
checkbox.parentElement.parentElement.remove(); // Remove item from the DOM
}
});
updateSummary();
document.getElementById("updateSelectedBtn").style.display = "none"; // Hide update button
};
const startEditingExpense = (expenseItem) => {
const name = expenseItem.querySelector("span").textContent.split(" (")[0];
const category = expenseItem.querySelector("span").textContent.split(" (")[1].slice(0, -1);
const amount = parseFloat(expenseItem.querySelector("span:last-of-type").textContent.split(" ")[1]);
document.getElementById("expenseName").value = name;
document.getElementById("expenseAmount").value = amount;
document.getElementById("expenseCategory").value = category;
editingExpenses.push(expenseItem);
document.getElementById("updateSelectedBtn").style.display = "inline-block";
document.getElementById("submitExpenseBtn").style.display = "none"; // Hide the add button
};
const resetForm = () => {
form.reset();
document.getElementById("submitExpenseBtn").style.display = "inline-block"; // Show add button
document.getElementById("updateSelectedBtn").style.display = "none"; // Hide update button
};
document.getElementById("toggleEditModeBtn").addEventListener("click", () => {
editMode = !editMode;
const editButton = document.getElementById("updateSelectedBtn");
editButton.style.display = editMode ? "inline-block" : "none"; // Show/Hide Edit button
document.getElementById("toggleEditModeBtn").textContent = editMode ? "Disable Edit Mode" : "Enable Edit Mode";
if (!editMode) {
editingExpenses = [];
resetForm();
}
});
document.getElementById("updateSelectedBtn").addEventListener("click", () => {
const expenseName = document.getElementById("expenseName").value.trim();
const expenseAmount = parseFloat(document.getElementById("expenseAmount").value);
const expenseCategory = document.getElementById("expenseCategory").value;
if (!expenseName || isNaN(expenseAmount)) {
return alert("Please enter valid expense details.");
}
editingExpenses.forEach(expenseItem => {
const previousAmount = parseFloat(expenseItem.querySelector("span:last-of-type").textContent.split(" ")[1]);
state.expenses += (expenseAmount - previousAmount); // Update total expenses based on new amount
// Update the item in the DOM
expenseItem.querySelector("span").textContent = `${toSentenceCase(expenseName)} (${toSentenceCase(expenseCategory)})`;
expenseItem.querySelector("span:last-of-type").textContent = `${state.currency} ${expenseAmount.toFixed(2)}`;
});
resetForm(); // Reset form and state after update
updateSummary();
});
document.getElementById("toggleDeleteModeBtn").addEventListener("click", () => {
deleteMode = !deleteMode;
const deleteButton = document.getElementById("deleteSelectedBtn");
deleteButton.style.display = deleteMode ? "inline-block" : "none"; // Show/Hide delete button
document.getElementById("toggleDeleteModeBtn").textContent = deleteMode ? "Disable Delete Mode" : "Enable Delete Mode";
if (!deleteMode) {
const checkboxes = document.querySelectorAll(".expense-checkbox");
checkboxes.forEach(checkbox => checkbox.checked = false);
}
});
document.getElementById("deleteSelectedBtn").addEventListener("click", deleteSelectedExpenses);
form.addEventListener("submit", (e) => {
e.preventDefault(); // prevent page refresh
const expenseName = document.getElementById("expenseName").value.trim();
const expenseAmount = parseFloat(document.getElementById("expenseAmount").value);
const expenseCategory = document.getElementById("expenseCategory").value;
if (!expenseName || isNaN(expenseAmount)) {
return alert("Please enter valid expense details.");
}
addExpenseToDOM(expenseName, expenseAmount, expenseCategory);
state.expenses += expenseAmount; // Add to total expenses
updateSummary();
resetForm(); // Clear the form inputs
});
document.getElementById("totalIncomeBtn").addEventListener("click", () => {
state.income = parseFloat(totalIncomeInput.value) || 0; // Handle empty input
updateSummary();
});
currencySelect.addEventListener("change", (e) => {
state.currency = e.target.value;
updateSummary();
});
document.getElementById("exportCsvBtn").addEventListener("click", () => {
const expensesData = [["Expense Name", "Category", "Amount"]];
document.querySelectorAll(".expense-item").forEach((item) => {
const name = item.querySelector("span").textContent.split(" (")[0];
const category = item.querySelector("span").textContent.split(" (")[1].slice(0, -1);
const amount = parseFloat(item.querySelector("span:last-child").textContent.split(" ")[1]);
expensesData.push([name, category, amount]);
});
const csvContent = expensesData.map((row) => row.join(",")).join("\n");
const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
const link = document.createElement("a");
link.setAttribute("href", URL.createObjectURL(blob));
link.setAttribute("download", "expenses.csv");
link.click();
});
document.getElementById("shareAppBtn").addEventListener("click", () => {
const shareText = "Check out this amazing Expense Tracker App!";
if (navigator.share) {
navigator.share({
title: "Expense Tracker",
text: shareText,
});
} else {
alert("Share functionality is not available in your browser.");
}
});
});
Summary of the Code
- Functionality: The application allows users to add, edit, and delete expenses. It also allows toggling between edit and delete modes for managing expenses.
- User Interface: The expenses are displayed in a user-friendly manner, making it easy to read and interact with. The edit and delete buttons are contextually used to maintain a clean layout.
- Data Export: Users can export the current list of expenses to a CSV file.
Testing Instructions
- Open the
index.html file in your browser.
- Add a few expenses using the form, and check that they appear in the list correctly.
- Try using the "Edit" and "Delete" functionalities to ensure they work properly.
- Finally, use the "Export to CSV" button to check that the CSV file generated contains the expected data.
If you encounter specific issues or errors during this process, please provide details, and I'll help troubleshoot further!