Skip to content

Instantly share code, notes, and snippets.

@jgwhite
Created June 10, 2012 15:59
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jgwhite/2906369 to your computer and use it in GitHub Desktop.
Save jgwhite/2906369 to your computer and use it in GitHub Desktop.
/* This function extracts user input from the Loan Calculator input form and uses it to set the variables of loanAmount, repayPeriod and protection*/
function getInput()
{
document.getElementById('error').style.display = 'none';
var loanAmount = document.getElementById('loan_amount').value;
/*Check whether user input for loan amount is valid*/
if (isNaN(loanAmount) == true || loanAmount<1000 || loanAmount>500000)
{
document.getElementById('error').style.display = 'block';
document.getElementById('loan_amount').value = "";
return false;
}
var selectedPeriod = document.getElementById("repay_period");
var selectedPeriod = selectedPeriod.options[selectedPeriod.selectedIndex].text;
var protection = false;
var repayPeriod = 0; //initialise repayPeriod variable
/*Convert the repay period selected from the drop-down list into the number of months in the repay period*/
if (selectedPeriod == "6 months")
{
repayPeriod = 6; //Deal with special case of 6 months
}
else
{
repayPeriod = parseInt(selectedPeriod.split(/\s+/)[0]) * 12; //extract number from repay period text and multiply by 12 to get months
}
/*Check if user has selected payment protection*/
if (document.forms[0].protect.checked)
{
protection = true;
}
calculateRepayment(loanAmount, repayPeriod, protection);
}
/*This function calls functions to calculate interest, payment protection and monthly payments and outputs to form*/
function calculateRepayment(loanAmount, repayPeriod, protection)
{
var interestRate = calculateInterestRate(loanAmount);
document.getElementById('rate').value =interestRate + "%";
var totalInterest = calculateInterest(loanAmount, repayPeriod, interestRate);
document.getElementById('total_interest').value = totalInterest;
}
/*This function uses the loan amount to determine the interest rate*/
function calculateInterestRate(loanAmount)
{
var baseRate = 4.25;
var rate = 0;
if (loanAmount <= 10000)
{
rate = baseRate + 5.5;
}
else if (loanAmount <= 50000)
{
rate = baseRate + 4.5;
}
else if (loanAmount <= 100000)
{
rate = baseRate + 3.5;
}
else
{
rate = baseRate + 2.5;
}
return rate;
}
function calculateInterest(loanAmount, repayPeriod, interestRate)
{
var interestYears = repayPeriod / 12;
var rate = interestRate / 100;
return loanAmount * rate * interestYears;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment