通过javascript计算输入字段的总和具有默认值属性

问题描述 投票:0回答:1

我在用javascript计算总和时遇到麻烦

这里是我的html代码:

Qty1 : <input class="txt" type="number" value="2" name="qty" id="qty1"/><br>
Qty2 : <input class="txt" type="number" value="4" name="qty" id="qty2"/><br>
Qty3 : <input class="txt" type="number" value="3" name="qty" id="qty3"/><br>
Qty4 : <input class="txt" type="number" value="5" name="qty" id="qty4"/><br>

和我的js代码

$(document).ready(function(){

  //iterate through each textboxes and add keyup
  //handler to trigger sum event
  $(".txt").each(function() {

    $(this).on('input',function(){
      calculateSum();
    });
  });

});

function calculateSum() {

  var sum = 0;
  //iterate through each textboxes and add the values
  $(".txt").each(function() {

    //add only if the value is number
    if(!isNaN(this.value) && this.value.length!=0) {
      sum += parseFloat(this.value);
    }

  });
  //.toFixed() method will roundoff the final sum to 2 decimal places
  $("#sum").html(sum.toFixed(2));

}

如果我直接在输入字段中输入数字,此代码仍然可以正常工作。但是,使用value属性,我希望在运行该程序时应立即返回结果。就我而言,当我运行程序时,它应该返回14,而不是0。我的jsfiddle链接:https://jsfiddle.net/tfrqh974/1/

javascript html
1个回答
1
投票

只需在calculateSum()中直接叫document.ready

$(document).ready(function() {

  $(".txt").each(function() {
    $(this).on('input', function() {
      calculateSum();
    });
  });
  calculateSum();
});


function calculateSum() {

  var sum = 0;

  $(".txt").each(function() {
    if (!isNaN(this.value) && this.value.length != 0) {
      sum += parseFloat(this.value);
    }

  });
  //.toFixed() method will roundoff the final sum to 2 decimal places
  $("#sum").html(sum.toFixed(2));

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Qty1 : <input class="txt" type="number" value="2" name="qty" id="qty1" /><br> Qty2 : <input class="txt" type="number" value="4" name="qty" id="qty2" /><br> Qty3 : <input class="txt" type="number" value="3" name="qty" id="qty3" /><br> Qty4 : <input class="txt"
  type="number" value="5" name="qty" id="qty4" /><br>
<div id="sum"></div>
© www.soinside.com 2019 - 2024. All rights reserved.