cusejuice
cusejuice

Reputation: 10671

Calculate Sum of Multiple Input Numbers JQuery

I have 3 inputs and I'm trying to get the sum of the numbers each time a user updates one of them.

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());

  });
});

But I keep getting crazy results..

EDIT:

I tried this:

  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);
    });
  });

Upvotes: 2

Views: 2328

Answers (1)

user1978142
user1978142

Reputation: 7948

Consider this example:

<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>

Upvotes: 2

Related Questions