Javascript表单计算

时间:2017-04-13 14:16:25

标签: javascript ajax forms calculator

我正在尝试在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新手,非常感谢您的反馈!

3 个答案:

答案 0 :(得分:0)

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

&#13;
&#13;
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.
});
&#13;
<form method="post" id="calculator">
  <input type="text" />
  <input type="submit" value="Calculate" />
</form>
&#13;
&#13;
&#13;

有关示例,请参阅此Fiddle

答案 1 :(得分:0)

问题是你使用的形式使用了我认为是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>

答案 2 :(得分:0)

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

接下来,没有名为note的HTML元素。那些应该是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>