2

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

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

This works thanks. I just tried another way (added an edit). Is there anything different from your example?
not much different too, if your personal preference is to add a method for computing the sum, its still okay.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.