【发布时间】:2017-08-07 03:40:43
【问题描述】:
我正在创建一个抵押贷款计算器,其中包含一个将计算分解为付款频率(每周、每两周、每月、每季度和每年)的计算,现在卡住了。
我尝试了许多不同的方法,但似乎没有什么对我有用。
我的脚本在下面。有人对我如何使它起作用有任何建议吗?
function computeLoan() {
//Prevent the Default Action eg, form to post/refresh the page
event.preventDefault();
var amount = parseInt(document.getElementById("amount").value);
var interest = calculateInterest(amount);
var term = parseInt(document.getElementById("years").value);
var frequency = document.getElementById("paymentTerm").value;
var finalAmmount = calculateMortgage(amount, interest, term, frequency);
document.getElementById("outMonthly").innerText = "$" + finalAmmount;
}
function calculateMortgage(p, r, n, f) {
r = percentToDecimal(r); //convert percentage to a decimal
n = yearsToMonths(n,f); //convert years to months
var pmt = (r * p) / (1 - (Math.pow((1 + r), (-n)))); //c=
((p*r)*Math.pow((1+r),n))/(Math.pow(1+r),n)-1
return parseFloat(pmt.toFixed(2));
}
function percentToDecimal(percent) { //Change the percent entered to
a decimal
return (percent / 12) / 100;
}
function yearsToMonths(year,frequency) {
//return year * 12;
if(frequency == "week"){
return year * 52;
}
if(frequency == "fortnight"){
return year * 26;
}
if(frequency == "quarter"){
return year * 4;
}
return year * 12;
}
function calculateInterest(amount){
var interest = 5.4;
if(amount > 200000 && amount < 250000){ //If loan amount is between $200,000 and $250,000, the interest rate will be 5.09%
interest = 5.09;
}
if(amount > 250000 && amount < 500000){ //If loan amount is between $250,000 and $500,000, the interest rate will be 4.84%
interest = 4.84;
}
if(amount > 500000 && amount < 750000){ //If loan amount is between $500,000 and $750,000, the interest rate will be 4.79%
interest = 4.79;
}
if (amount > 750000){ //If loan amount is greater than $750,000, the interest rate will be 4.50%
interest = 4.50;
}
return interest;
}
function postPayments(payment) {
var htmlEl = document.getElementById("outMonthly");
htmlEl.innerText = "$" + payment;
// document.getElementById("outMonthly").innerText = payment;
return;
}
form{
text-align: center;
border: 2px black solid;
}
<form onsubmit="computeLoan();">
<legend>Mortgage Calculator</legend>
<p><b>Number of Years</b>: <input type="text" id="years" value="30"
required></p>
<p><b>Loan Amount</b>: <input type="text" id="amount" value="200000"
required></p>
<p><b>Payment Frequency :</b>
<select id='paymentTerm'>
<option value="week">Weekly</option>
<option value="fortnight">Fortnightly</option>
<option value="month">Monthly</option>
<option value="quarter">Quarterly</option>
<option value="year">Yearly</option>
</select>
</p>
<input type="submit">
<p><b>The repayment amount is <span id="outMonthly"></span> each <span
id="paymentTermOut"></span></b></p>
</form>
【问题讨论】:
-
有什么问题?
-
如果没有更改频率的选项(每周、每两周、每月、每季度、每年),计算将按照我的意愿进行。当我将不同的频率添加到代码的计算中时,它计算不正确。作为 Javascript 新手,我不确定自己哪里出错了。
标签: javascript html calculator