计算多输入数JQuery的总和

时间:2014-05-06 00:37:15

标签: javascript jquery

我有3个输入,我试图在每次用户更新其中一个时获得数字的总和。

HTML

<input class="my-input" type="number" name="" value="0" min="0">
<input class="my-input" type="number" name="" value="0" min="0">
<input class="my-input" type="number" name="" value="0" min="0">

JS

var sum = 0;
$('.my-input').each(function(index, elem){
  var value = $(this).val();

  sum += parseFloat($(elem).val());
  console.log(sum);

  $(this).on('keyup click', function (){

    sum += parseFloat($(elem).val());

  });
});

但我一直在疯狂的结果......

编辑:

我试过了:

  function getSum(){
    var sum = 0;
    $('.my-input').each(function(index, elem){
      var value = $(this).val();

      sum += parseFloat($(elem).val());

    });

     return sum;
  }

  $('.my-input').each(function(){
    $(this).on('keyup click', function(){
      console.log( this.value );
      var curSum = getSum();

      console.log('current sum: ' + curSum);
    });
  });

1 个答案:

答案 0 :(得分:2)

考虑这个例子:

<input class="my-input" type="number" name="" value="0" min="0" />
<input class="my-input" type="number" name="" value="0" min="0" />
<input class="my-input" type="number" name="" value="0" min="0" />
<input type="text" id="total" value="" />

<script type="text/javascript">
// just get keyup event
$('.my-input').on('keyup', function(){
    var total = 0;
    // on every keyup, loop all the elements and add all the results
    $('.my-input').each(function(index, element) {
        var val = parseFloat($(element).val());
        if( !isNaN( val )){
           total += val;
        }
    });
    $('#total').val(total);
});
</script>