我开始学习编码并尝试创建贷款/抵押贷款计算器作为我学习的一部分。我试图通过利用Highcharts来绘制结果更进一步,但无法按照我的意愿使其工作。
理想情况下,我希望馅饼能够使用计算的新值动态更新(即"每月还款"和"仅每月利息")。
到目前为止,我只能通过点击"计算"来重新绘制它。按钮,但只有在按下按钮至少两次时才会使用正确的新值进行更新。
示例:https://codepen.io/sonofauley/pen/rwNLom
<body onload="calculate();">
<form method="POST" name="calc" onsubmit="calculate(); return false;">
<label>Amount</label>
<input type="textbox" id="loan" value="100000"><br>
<label>Years</label>
<input type="textbox" id="years" value="25"><br>
<label>Rate (%)</label>
<input type="textbox" id="rate" value="2.50" onkeyup="calculate"><br>
<input type="submit" value="Calculate" id="btn"><br>
<label>Monthly Repayment</label>
<input type="textbox" id="monthlyRepayment"><br>
<label>Monthly Interest Only</label>
<input type="textbox" id="interest"><br>
<label>Monthly Capital Repayment</label>
<input type="textbox" id="capitalRepayment">
<label>Total Interest</label>
<input type="textbox" id="totalInterest"><br>
</form>
<div id="container" style="height: 300px"></div>
</body>
//the below script is in its own js file "cacl.js"
$(document).on("keyup", calculate());
function calculate() {
var p = document.querySelector("#loan").value;
var years = document.querySelector("#years").value;
var rate = document.querySelector("#rate").value;
var r = rate / 100 / 12;
var n = years * 12;
var m1 = r * Math.pow(1 + r, n);
var m2 = Math.pow(1 + r, n) - 1;
var m = (p * (m1 / m2)).toFixed(2);
var I = ((p - n) / m).toFixed(2);
var ti = m * n - p;
var mr = (m - I).toFixed(2);
document.querySelector("#monthlyRepayment").value = m;
document.querySelector("#interest").value = I;
document.querySelector("#totalInterest").value = ti;
document.querySelector("#capitalRepayment").value = mr;
}
//the below script is in a separate js file "chart.js"
$(function () {
$('#btn').click(function(){
var val1,
val2,
options;
val1 = parseFloat($('input[id=monthlyRepayment]').val());
val2 = parseFloat($('input[id=capitalRepayment]').val());
options = {
series: [{
type: 'pie',
name: 'Browser share',
data: [val1,val2]
}]
};
$('#container').highcharts(options);
});
});
答案 0 :(得分:0)
计算出的值不正确会导致图表形成错误。实际上,您必须在按钮点击功能上调用calculate()
用此
替换现有(部分)$(function() {
$('#btn').click(function() {
calculate();
var val1,
val2,
options;
val1 = parseFloat($('input[id=monthlyRepayment]').val());
val2 = parseFloat($('input[id=capitalRepayment]').val());
options = {
series: [{
type: 'pie',
name: 'Browser share',
data: [{name:"Monthly Repayment",y:val1},{name:"Capital Repayment",y:val2}]
}]
};
$('#container').highcharts(options);
});
});
codepen演示