loanCalculator

First project for ICS 314

by butterfreeDay

HTML

<!DOCTYPE html>
<html>
    <!--
    This html file makes use of getMonths() function in the monthsLoan.js
    -->
    <head>
        <script type="text/javascript" src="monthsLoan.js">
        </script>
        <script type="text/javascript">
            document.addEventListener('DOMContentLoaded',init);
            function removeChildren(elem){
                while (elem.childNodes.length > 0) {
                    elem.removeChild(elem.childNodes[0]);
                }
            }
            function calcMonths(){
                //console.log("calcMonths() called");
                const amountBox = document.getElementById("amount");
                const borrowedBox = document.getElementById("borrowed");
                const rateBox = document.getElementById("rate");
                const answers = document.getElementById("answers");
                removeChildren(answers);
                let amount = Number(amountBox.value);
                let borrowed = Number(borrowedBox.value);
                let rate = Number(rateBox.value);
                //console.log(getMonths(amount,borrowed,rate));
                let months = getMonths(amount,borrowed,rate);
                // will return NaN if months is an infinite value
                if (isNaN(months) === true) {
                    //console.log("Your monthly payment is too small.");
                    let li = document.createElement("li");
                    let msg = "That loan payment is so small, it would take forever to pay off the loan";
                    li.appendChild(document.createTextNode(msg));
                    answers.appendChild(li);
                }
                //months will be a valid number
                else {
                    let li= document.createElement("li");
                    let msg = "The number of months to pay off loan would be " + months.toFixed(2);
                    li.appendChild(document.createTextNode(msg));
                   ...

JavaScript

/*
 *Author: Taryn Takebayashi
 * This function is used to calculate the number of months it would
 * take to pay off a loan given the following:
 * payment - monthly payment
 * borrowed - amount borrowed
 * rate - annual interest rate. Enter in decimal form.
*/
function getMonths(payment,borrowed,rate) {
    let r = rate/12;
    let months = Math.log(payment/(payment - (borrowed*r)))/Math.log(1+r);
    return months;
}
//console.log(getMonths(40,500,0.1));