简体   繁体   中英

Calculating sum only for relevant row

So I have problem which I can't solve for hours now..

When I press on button "Pridėti prekę" then one row is dynamically added to the table and when I write numbers in "Kiekis" and "Kaina" columns nothing happens in "Suma" column (It only happens to dynamically added row).

Piece of jQuery:

$(document).on('keyup', '#quantity, #price', function() {
    $('#total').val(($('#quantity').val() * $('#price').val()).toFixed(2));
});

Please look at JSFiddle how is "working" my code:

https://jsfiddle.net/w5qz5exe/7/

Thanks for help in advance!

PS I tried to change from div ID total, to div class total, then it works, but it applies to all rows instead to relevant.

You were referencing everything with id's.

    $(document).on('keyup', '.quantity, .price', function() {
        var row = $(this).closest('tr');
        var rowPrice = $(row).find('.price').val();
        var rowQuantity = $(row).find('.quantity').val();

        $(row).find('.total').val( (rowPrice * rowQuantity).toFixed(2) )
    });

https://jsfiddle.net/w5qz5exe/12/

Your problem is the fact that the inputs are using id's instead of something else. When looking for the item in question the search stops on the first Id found.

This updated fiddle https://jsfiddle.net/w5qz5exe/11/ shows how it could be done with classes.

        $(document).on('keyup', '.quantity, .price', function(e) {
            var $parent = $(e.target).parents('tr'),
                $total = $parent.find('.total'),
                $quantity = $parent.find('.quantity'),
                $price = $parent.find('.price');
            $total.val(($quantity.val() * $price.val()).toFixed(2));
        });

In addition to the above remove all Id's from the inputs and change them to classes instead.

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