简体   繁体   中英

sum of dynamically added readonly input box using javascript

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM