Javascript表格计算

Javascript Form Calculation

我正在尝试在 javascript 中制作一个表格来计算抵押贷款,然后将结果呈现到页面上。 这是我的表格:

<form name="calc" id="lidd_mc_form" class="lidd_mc_form" method="post">
<div class="lidd_mc_input mortgage lidd_mc_input_light lidd_mc_input_responsive"><label for="lidd_mc_total_amount">Mortgage Required <note style="color: grey;">(omit commas)</note></label><input type="text" name="lidd_mc_total_amount" id="lidd_mc_total_amount" placeholder="£"><span id="lidd_mc_total_amount-error"></span></div><div class="lidd_mc_input down_payment lidd_mc_input_light lidd_mc_input_responsive"><div style="visibility: hidden; position: absolute;"><label for="lidd_mc_down_payment">Down Payment</label><input type="text" name="lidd_mc_down_payment" id="lidd_mc_down_payment" placeholder="£"><span id="lidd_mc_down_payment-error"></span></div></div><div class="lidd_mc_input interest_rate lidd_mc_input_light lidd_mc_input_responsive"><label for="lidd_mc_interest_rate">Interest Rate <note style="color: grey;">(enter 10% as 10)</note></label><input type="text" name="lidd_mc_interest_rate" id="lidd_mc_interest_rate" placeholder="%"><span id="lidd_mc_interest_rate-error"></span></div><div class="lidd_mc_input amortization_period lidd_mc_input_light lidd_mc_input_responsive"><label for="lidd_mc_amortization_period">Repayment Period <note style="color: grey;">(omit commas)</note></label><input type="text" name="lidd_mc_amortization_period" id="lidd_mc_amortization_period" placeholder="years"><span id="lidd_mc_amortization_period-error"></span></div>
<input type="hidden" name="lidd_mc_payment_period" id="lidd_mc_payment_period" value="12"><div class="lidd_mc_input">

<input type="button" onclick="calc()" name="lidd_mc_submit" id="lidd_mc_submit" value="Calculate"></div></form>

<div id="lidd_mc_details" class="lidd_mc_details" style="display: none;"><div id="lidd_mc_results" class="lidd_mc_results"></div>
                <div id="lidd_mc_summary" class="lidd_mc_summary lidd_mc_summary_light" style="display: block;"></div>
            </div>

这是我正在使用的Javascript:

            <script>
    function calc() {   /**  * Created by Connor on 13/04/2017.  */


        var mortgageRequired = document.forms["calc"]["lidd_mc_total_amount"].value;
        var interestRate = document.forms["calc"]["lidd_mc_interest_rate"].value;
        var repaymentPeriod = document.forms["calc"]["lidd_mc_amortization_period"].value;


//Calculation

//calculate repayment period in months
        var repaymentMonthly = repaymentPeriod * 12;

//Capital Payment
        var capitalPayment = mortgageRequired * (((interestRate / 12) * (1 + interestRate / 12) ^ repaymentMonthly) /
            ((1 + (interestRate / 12)) ^ repaymentMonthly - 1));

//Interest Only
        var noInterest = mortgageRequired / repaymentMonthly;
        var interestOnly = capitalPayment - noInterest;

//Display
        document.getElementById('lidd_mc_details').innerHTML +=
            interestOnly & capitalPayment;


 } </script>

问题是页面会刷新,而且根本不起作用,因为它不会向页面呈现任何内容,即使输入是提交按钮

我也在努力使代码不会刷新用户页面并且是异步的,这样做是否正确?

我是 JavaScript 的新手,非常感谢任何反馈!

您需要将函数绑定到表单的提交事件以阻止页面重新加载。您可以通过在表单元素上使用 addEventListner('submit', function(e) { .. }); 来完成此操作。您将使用 e.preventDefault() 停止表单的提交事件,然后您可以继续计算和输出。

var form = document.getElementById('calculator');

form.addEventListener('submit', function(e) {
  // Prevent Default will stop the event from firing
  e.preventDefault();
  // Run your calculations here etc.
});
<form method="post" id="calculator">
  <input type="text" />
  <input type="submit" value="Calculate" />
</form>

查看此 Fiddle 示例。

问题是您使用的表单使用了我假设为 php 的方法。默认情况下,这将刷新页面。您希望在不发出任何网络请求的情况下处理所有内容,因此使用 DOM 操作应该可以完成这项工作。下面是一个工作示例。

 function calc() {   /**  * Created by Connor on 13/04/2017.  */


        var mortgageRequired = document.getElementById("lidd_mc_total_amount").value;
        var interestRate = document.getElementById("lidd_mc_interest_rate").value;
        var repaymentPeriod = document.getElementById("lidd_mc_amortization_period").value;


//Calculation

//calculate repayment period in months
        var repaymentMonthly = repaymentPeriod * 12;

//Capital Payment
        var capitalPayment = mortgageRequired * (((interestRate / 12) * (1 + interestRate / 12) ^ repaymentMonthly) /
            ((1 + (interestRate / 12)) ^ repaymentMonthly - 1));

//Interest Only
        var noInterest = mortgageRequired / repaymentMonthly;
        var interestOnly = capitalPayment - noInterest;

//Display
        document.getElementById('lidd_mc_details').innerHTML +=
            interestOnly & capitalPayment;


 } 
<html>
  <body>
  lidd_mc_total_amount
  <input type="text" id="lidd_mc_total_amount"/>
  <br>
  lidd_mc_interest_rate
  <input type="text" id="lidd_mc_interest_rate"/>
  <br>
  lidd_mc_amortization_period
  <input type="text" id="lidd_mc_amortization_period"/>
  <br>
  <button onClick="calc()">Click for answer</button>

  <div>The answer: <span id="lidd_mc_details"></span></div>
  
  </body>
</html>

页面正在刷新,因为您正在使用配置了 method 属性的 form 元素。表单用于将数据传输到服务器资源,这不是您在此处尝试执行的操作。在这种情况下,您需要禁用表单的提交功能,您可以通过删除 method 属性来实现。

接下来,没有 HTML 个名为 note 的元素。这些应该是 span 个元素。

接下来,您将在末尾使用 & 进行串联。这应该是 +.

此外,不要使用内联 HTML 事件处理程序(onclick、onmouseover 等),因为它们会创建意大利面条代码,导致隐式全局包装函数改变 this 绑定的创建和不要遵循 W3C 事件标准。使用 addEventListener 绑定 JavaScript 中的事件处理程序。

最后,您的结果区域 CSS 样式设置为 display:none,因此您在单击按钮后看不到任何内容。单击按钮后,您需要对其进行修改。

这是修改后的版本(见评论):

// These should not be in the function. You only need to scan the DOM for them once.

// Don't set your variables to the values of the input fields. Instead set them to the
// input fields themselves. That way, you can go back and get any other property of the
// field without having to scan the DOM for the element again.  Also, get the reference
// to the element using the more modern approach (i.e. document.getElementById()).
var mortgage = document.getElementById("lidd_mc_total_amount");
var interest = document.getElementById("lidd_mc_interest_rate");
var repayment = document.getElementById("lidd_mc_amortization_period");
var button = document.getElementById("lidd_mc_submit");
var output = document.getElementById('lidd_mc_details');

// Set up event handler for button
button.addEventListener("click", calc);

// The name of the function should not be in parenthesis.
function calc(){ 
  
  // Now, set up variables for the values and remember that all input element values are strings
  // by default and need conversion to numbers before math is done with them.
  var mortgageRequired = parseFloat(mortgage.value);
  var interestRate = parseFloat(interest.value) / 1200;    // Convert to decimal and get periodic rate
  var repaymentPeriod = parseFloat(repayment.value) * 12;  // Get period in months

  //Calculation

  //Capital Payment
  var capitalPayment = mortgageRequired * interestRate * 
                      (Math.pow(1 + interestRate, repaymentPeriod)) / 
                      (Math.pow(1 + interestRate, repaymentPeriod) - 1);

  //Display
  // Use textContent instead of innerHTML when the output doesn't contain HTML
  // and don't use & to concatenate in JavaScript as & means logical "AND", not concatenate
  output.style.display = "block";
  output.textContent = capitalPayment.toFixed(2);
 }
<form name="calc" id="lidd_mc_form" class="lidd_mc_form">
  <div class="lidd_mc_input mortgage lidd_mc_input_light lidd_mc_input_responsive">
    <label for="lidd_mc_total_amount">
      Mortgage Required <span style="color: grey;">(omit commas)</span>
    </label>
    <input type="text" name="lidd_mc_total_amount" id="lidd_mc_total_amount" placeholder="£">
    <span id="lidd_mc_total_amount-error"></span>
  </div>
  <div class="lidd_mc_input down_payment lidd_mc_input_light lidd_mc_input_responsive">
    <div style="visibility: hidden; position: absolute;">
      <label for="lidd_mc_down_payment">Down Payment</label>
      <input type="text" name="lidd_mc_down_payment" id="lidd_mc_down_payment" placeholder="£">
      <span id="lidd_mc_down_payment-error"></span>
    </div>
  </div>
  <div class="lidd_mc_input interest_rate lidd_mc_input_light lidd_mc_input_responsive">
    <label for="lidd_mc_interest_rate">
      Interest Rate <span style="color: grey;">(enter 10% as 10)</span>
    </label>
    <input type="text" name="lidd_mc_interest_rate" id="lidd_mc_interest_rate" placeholder="%">
    <span id="lidd_mc_interest_rate-error"></span>
  </div>
  <div class="lidd_mc_input amortization_period lidd_mc_input_light lidd_mc_input_responsive">
    <label for="lidd_mc_amortization_period">
      Repayment Period <span style="color: grey;">(omit commas)</span>
    </label>
    <input type="text" name="lidd_mc_amortization_period" id="lidd_mc_amortization_period" placeholder="years">
    <span id="lidd_mc_amortization_period-error"></span>
  </div>
  <input type="hidden" name="lidd_mc_payment_period" id="lidd_mc_payment_period" value="12">
  <div class="lidd_mc_input">
    <input type="button" name="lidd_mc_submit" id="lidd_mc_submit" value="Calculate">  </div>
</form>

<div id="lidd_mc_details" class="lidd_mc_details" style="display: none;">
  <div id="lidd_mc_results" class="lidd_mc_results"></div>
  <div id="lidd_mc_summary" class="lidd_mc_summary lidd_mc_summary_light" style="display: block;">   
  </div>
</div>