我试图用下拉框制作汽车贷款计算器。您输入您想借入的金额,然后出现一个下拉利率,利率为6.75%或9.71%。然后输入您想要偿还贷款的月数。然而,它似乎没有正常工作,它不会给出两个不同数字的结果。什么时候给6.75%的结果答案是错的我的JavaScript有什么问题吗?我以为我可能会以错误的顺序拥有它?我已经做了我能想到的一切而且它没有用?
这是html
<html>
<body>
<p>Loan Amount: €<input id="amount" type="number" min="1" max="1000000" onchange="computeLoan()"></p>
<p>Interest Rate:
<select id= "rate" onchange="computeLoan()">
<option value="" disabled="disabled" selected="selected">Select A Loan Rate</option>
<!-- 6.75 loan -->
<option value="6.75" input id="interest_rate">6.75%</option>
<!-- 9.71 loan -->
<option value="9.71" input id="interest_rate">9.71%</option>
</select></p>
<p>Months: <input id="months" type="number" min="1" max="60" value="1" step="1" onchange="computeLoan()"></p>
<h2 id="payment"></h2>
</body>
</html>
的javascript
//条件逻辑
function computeLoan(){
// grab the selected value of the dropdown box
var r = document.getElementById("rate");
var rateSelected = r.options[r.selectedIndex].value;
var interest_rate = document.getElementById('interest_rate').value;
//grab elements by their ID
var amount = document.getElementById('amount').value;
var months = document.getElementById('months').value;
document.getElementById("interest_rate").value=rateSelected;
//do the maths do find the percentage
var interest = (amount * (interest_rate * .01)) / months;
//bring results to two decimal places
var payment = ((amount / months) + interest).toFixed(2);
payment = payment.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
// display the results
document.getElementById('payment').innerHTML = "Your Monthly Payment = €"+payment;
}
答案 0 :(得分:0)
尝试以下代码:
var interest = (parseFloat(amount) * (parseFloat(interest_rate) * .01)) / parseFloat(months);
答案 1 :(得分:0)
替换逻辑中的这些代码行,您必须First convert the string format into numbers and then do the math
。
var rateSelected = parseFloat(r.value); // no need of r.options[r.selectedIndex].value
var interest_rate = parseFloat(document.getElementById('interest_rate').value);
//grab elements by their ID
var amount = parseFloat(document.getElementById('amount').value);
var months = parseFloat(document.getElementById('months').value);
稍后当你进行数学运算时,事情必须按预期工作。