0

I am trying to calculate the sum of all input boxs' value

<input class='total' type='number' name='total[]' readonly>

(which are readonly and whose values are also got from another javascript calculation function).

I have this jsFiddle

I used the following javascript to sum all the values of a readonly input box. It does not seem to work.

var $form = $('#invEntry'),
    $sumDisplay = $('#totaldp');

$form.delegate('.total', 'change', function ()
{
    var $summands = $form.find('.total');
    var sum = 0;
    $summands.each(function ()
    {
        var value = Number($(this).val());
        if (!isNaN(value)) sum += value;
    });

    $sumDisplay.val(sum);
});
1
  • would it not be better to ad an ID to your tr rows or working with a hidden field where you store a counter of items. ( you would like to know how many items are on the invoice correct? ) Commented May 20, 2014 at 11:48

1 Answer 1

1

It is because the 'change' event is only raised when a user changes the value in the text box, not when it's changed by DOM manipulation. You could trigger the calculation from your update of the total textboxes.

 $("#InputsWrapper").on('change', '.discount',function(){
     var tr = $(this).closest('tr');
     var quantity=tr.find(".qty").val();
     var percent=tr.find(".discount").val();
     var price=tr.find(".price").val();
     var tprice = price * quantity
     var discountpercent=percent / 100;
     var discountprice=(tprice * discountpercent );

     tr.find(".total").val(tprice - discountprice);
     calculateTotals()
});

function calculateTotals()
{
    var $summands = $('#invEntry').find('.total');
    var sum = 0;
    $summands.each(function ()
    {
        var value = Number($(this).val());
        if (!isNaN(value)) sum += value;
    });

    $('#totaldp').val(sum);
}
Sign up to request clarification or add additional context in comments.

3 Comments

how do I trigger it? I am new to JS.
Well you could rename your $form.delegate('.total', 'click', function () as a standard function (e.g. called calculateTotals) and call it from your $("#InputsWrapper").on('change', '.discount',function(){
You would write a lot less code relating to events if you used knockout.js to bind the UI to a set of javascript objects. Here is a JS fiddle of how it might work: jsfiddle.net/t92Z9

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.