I'm new to programming and cannot figure out how to use the global variables in my code correctly. I'm trying to use the global variables as my parameters when I call certain functions. What can I do to make this work? Any suggestions or advice would be much appreciated thank you.
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Loan Calculator</title>
<script type="text/javascript">
/* Input: Get the principal, intrest rate, years, payments per year and number of payments to date
* Processing: Calculating the monthly payment of a loan and loan payoff amount
* Output: The monthly payment and payoff amount
*/
var inv = document.getElementById("invest").value;
var r = document.getElementById("rate").value;
var num = document.getElementById("numyear").value;
var per = document.getElementById("periods").value;
var pay = document.getElementById("pay").value;
var invest = parseFloat(inv);
var rate = parseFloat(r);
var numyear = parseFloat(num);
var periods = parseFloat(per);
var paytodate = parseFloat(pay);
function doPayment() {
var result = computePayment(invest, rate, numyear, periods);
document.getElementById("output").innerHTML = result;
}
function doBalance() {
var result = computeBalance(invest, rate, numyear, periods, paytodate);
document.getElementById("secondOut").innerHTML = result;
}
function computePayment(principal, annualRate, years, periodsPerYear) {
var p = (principal * annualRate / periodsPerYear) / (1 - Math.pow((1 + annualRate / periodsPerYear), -years * periodsPerYear));
return p.toFixed(2);
}
function computeBalance(principal, annualRate, years, periodsPerYear, numberOfPaymentsPaidToDate) {
var r = computePayment(invest, rate, numyear, periods);
var f = principal * (Math.pow(1 + annualRate / periodsPerYear, numberOfPaymentsPaidToDate)) -
(r * ((Math.pow(1 + annualRate / periodsPerYear, numberOfPaymentsPaidToDate)) - 1) / (annualRate / periodsPerYear));
return f.toFixed(2);
}
</script>
</head>
<body>
<h1>Loan Calculator</h1><br>
Amount Borrowed <input type="text" id="invest" size="5"> <br>
Annual Rate <input type="text" id="rate" size="5"><br>
Number of years <input type="text" id="numyear" size="5"><br>
Payments per year <input type="text" id="periods" size="5"><br>
Number of payments paid to date <input type="text" id="pay" size="5"><br>
<button type="button" onclick="doPayment()">Payment</button> <div id="output"></div> <br>
<button type="button" onclick="doBalance()">Payoff amount</button><div id="secondOut"></div><br>
<input type="button" value="Reset Form" onClick="reset"<button/>
</body>
</html>