<!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));
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.