0

I have written the following script. The first part multiplies the quantity and cost per item in a row, and adds it as the value in the ".price" input.

The second part I am attempting to dynamically update the #total value as each .price is added. But I can't get this part to work.

var total; 
$('.invoice').on('focus','.current' , function(){
    // Calculate Price
    $('.qty').keyup(function(){
        var qty = $( document.activeElement ).val();
        var value = $( document.activeElement ).siblings(".cost").val();
        $( document.activeElement ).siblings(".price").val(qty * value);
    });
    // Calculate Total
    $('.price').change(function(){
           $('.price').each(function(){
              price = $('.price').val();
              total = parseInt(total) || 0 + parseInt(price) || 0;
              $('#total').val(total);
           });
    });
});
4
  • 1
    could you please add your html also. thanks. Commented Oct 11, 2015 at 4:05
  • 1
    You would need to declare total before the each loop and use total = total + price; and then assign the total after the each loop. But why are you .keyup() and .change() functions inside the on() function? Commented Oct 11, 2015 at 4:06
  • Also please post your html code. Commented Oct 11, 2015 at 4:24
  • I'm guessing you want something like this fiddle? Commented Oct 11, 2015 at 4:28

1 Answer 1

1

your calculate total part should be like below

 $('.price').change(function() {
   var total = 0;
   $('.price').each(function() {
     price = $('.price').val();
     total += parseInt(total) || 0 + parseInt(price) || 0;
   });
   $('#total').val(total);
 });

Declare the variable total outside each loop and sum all values and append to #total after each loop (not in each loop).

Sign up to request clarification or add additional context in comments.

Comments

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.