<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width" />
<title>Hello, world!</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Hello, world!</h1>
<label for="var1">House Price:</label>
<input type="number" id="var1" required>
<br>
<label for="var2">Yearly Interest:</label>
<input type="number" id="var2" required>
<br>
<label for="var3">Mortgage Years:</label>
<input type="number" id="var3" required>
<br>
<br>
<button id="run">Calculate</button>
<br>
<p id="debug"></p>
<p id="result"></p>
<script>
function calculateMortgage() {
// Get user inputs from HTML elements
const housePriceInput = document.getElementById("var1");
const yearlyInterestInput = document.getElementById("var2");
const mortgageYearsInput = document.getElementById("var3");
const housePrice = parseFloat(housePriceInput.value);
const yearlyInterest = parseFloat(yearlyInterestInput.value);
const mortgageYears = parseInt(mortgageYearsInput.value);
// Validate input values
if (isNaN(housePrice) || housePrice <= 0 || isNaN(yearlyInterest) || yearlyInterest <= 0 || isNaN(mortgageYears) || mortgageYears <= 0) {
alert("Please enter valid numbers for all fields.");
return;
}
// Display the result in the HTML
const debugElement = document.getElementById("debug");
debugElement.textContent = `Var1: $${housePrice.toFixed(2)}, Var2: ${yearlyInterest.toFixed(4)}, Var3: ${mortgageYears}.`;
// Calculate the total cost
let overallPrice = housePrice;
for (let i = 0; i < mortgageYears; i++) {
overallPrice += overallPrice * yearlyInterest;
}
// Calculate the monthly mortgage payment
const mortgagePayment = (overallPrice) / (mortgageYears * 12);
const mortgagePrice = (overallPrice - housePrice) / (mortgageYears * 12);
// Display the result in the HTML
const resultElement = document.getElementById("result");
resultElement.textContent = `Mortgage Payment: $${mortgagePayment.toFixed(2)}, Price: $${mortgagePrice.toFixed(2)}.`;
}
// Attach an event listener to the calculate button
const calculateButton = document.getElementById("run");
calculateButton.addEventListener("click", calculateMortgage);
</script>
</body>
</html>