JSFiddle - React, Tailwind, and code Playground
by Tan
HTML
<table class="cwCalc" border=0 cellpadding=0 cellspacing=0 width=400>
<tr><th>What will it take to pay off my credit card?</th></tr>
<tr><td align=center>
<table cellpadding=2 cellspacing=0>
<tr><td align="right">Enter your credit card balance: $</td><td><input size=6 type=text id="cwBalance"></td></tr>
<tr><td align="right">Enter the credit card's interest rate: </td><td><input size=6 type=text id="cwRate">%</td></tr>
<tr><td align="right">Enter payment amount per month: $</td><td><input size=6 type=text id="cwMonthlyAmount"></td></tr>
<tr><td align="center"><b>or</b></td><td> </td></tr>
<tr><td align="right">Enter desired months until debt free: </td><td><input size=6 type=text id="cwDesiredMonths"></td></tr>
<tr><td colspan=2 align="center"><input type=button value="Calculate" onclick="cwCalc();"></td></tr>
<tr><td colspan=2 align="center" id="cwResult"></td></tr>
</table>
</td></tr>
</table>
CSS
.cwCalc{border:1px solid black;}
.cwCalc TH{background-color:#BBBBBB;}
.cwCalc TD{background-color:#DDDDDD;}
JavaScript
<!-- Credit Card Calculator with estimated months to pay off -->
function cwCalc()
{
if (cwBalance.value=='') {alert('Please enter your credit card balance.'); return;}
if (cwRate.value=='') {alert('Please enter your credit card\'s interest rate.'); return;}
if ( (cwMonthlyAmount.value=='' && cwDesiredMonths.value=='') || (cwMonthlyAmount.value!='' && cwDesiredMonths.value!='') ) {alert('Please enter either a payment amount or desired months.'); return;}
var mRate=(cwRate.value/100)/12;
if (cwMonthlyAmount.value=='')
{
var payment=cwBalance.value*(mRate)/( 1-Math.pow((1+mRate),(-cwDesiredMonths.value)) );
payment=Math.round(payment*100)/100;
cwResult.innerHTML="It will cost $" + payment.toFixed(2) + " a month to pay off this card and will cost you a total of $" + (payment*cwDesiredMonths.value).toFixed(2) + ".";
} else {
var remainingBalance=cwBalance.value;
var minPayment=mRate*cwBalance.value;
var months=0;
var lastPayment;
if (minPayment>cwMonthlyAmount.value) {alert ('Your monthly payment is less than the monthly interest charged by this card.');return;}
while (remainingBalance>0)
{
months++;
remainingBalance=remainingBalance*(1 + mRate)-cwMonthlyAmount.value;
}
cwResult.innerHTML="It will take " + months + " months to pay off this card and will cost you a total of $" + (cwMonthlyAmount.value*months).toFixed(2) + ".";
}
}
// End -->