首页 > 解决方案 > 单击计算按钮后,javascript代码不显示未来值的答案

问题描述

我正在研究 fv 计算器。但是,我不知道为什么我的 JavaScript 代码在单击计算按钮后不显示未来值的答案。

我该如何解决这个问题?

如果有人可以为我提供帮助,我将不胜感激,谢谢。

下面是我的 HTML 和 JavaScript 代码。

<html>
  <head>
    <title>401K Future Value Calculator</title>
    <script type="text/javascript" src="mpg.js"></script>
  </head>

  <body>
    <h2>401K Future Value Calculator</h2>

    <form id="calculationForm" >
      <label for="periodicPayment">Yearly Investment($): </label>
      <select id="yearlyInvest" name="Investment”">
        <option value="1000: ">1000</option>
        <option value="2000: ">2000</option>
        <option value="3000: ">3000</option>
        <option value="4000: ">4000</option>
        <option value="5000: ">5000</option>
        <option value="6000: ">6000</option>
        <option value="7000: ">7000</option>
        <option value="8000: ">8000</option>
        <option value="9000: ">9000</option>
        <option value="10000: ">10000</option>
      </select><br><br>

      <label for="annunalInterest">Annual Interest Rate(%) </label>
      <input type="text" id="annunalInterestRate"><br><br>

      <label for="years">Number of Years(#) </label>
      <input type="text" id="numOfYears"><br><br>

      <label for="future">Future Value($) </label>
      <p id="futureValue">       
      </p>

      <input type="button" id="calculate" value="Calculate">
      <input type="button" onclick="clearButton()" id="clear" value="Clear">
    </form>
  </body>
</html>
function processForm() {

  var r, n, p;

  r = parseFloat(document.getElementById("annunalInterestRate").value);
  n = parseInt(document.getElementById("numOfYears").value);
  p = document.getElementById("yearlyInvest").value;

  if (isNaN(r)) {
    alert("Pleas enter a valid number.");
  } else if (isNaN(n)) {
    alert("Pleas enter a valid number.");
  } else {
    var fv = P * ((Math.pow((1 + r), n) - 1) / r);
  }
  document.getElementById("calculate").value;
  document.getElementById("futureValue").innerHTML = fv.toFixed(2);
};

window.onload = function() {
  document.getElementById("calculate").onclick = processForm;
};

function clearButton() {
  document.getElementById("calculationForm").reset();
}

标签: javascript

解决方案


您在参数中编写<option>节点的方式<select>包含不必要:的内容value=。这导致p计算为NaN。相反,重写为:

<select id="yearlyInvest" name="Investment”">
        <option value="1000">1000</option>
        <option value="2000">2000</option>
        ...
</select>

推荐阅读