简体   繁体   English

仅计算相关行的总和

[英]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). 当我按下按钮“Pridėtiprekę”时,一行会动态添加到表中,当我在“ Kiekis”和“ Kaina”列中写数字时,“ Suma”列中什么也不会发生(仅发生在动态添加的行中)。

Piece of jQuery: 一块jQuery:

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

Please look at JSFiddle how is "working" my code: 请查看JSFiddle,它如何“工作”我的代码:

https://jsfiddle.net/w5qz5exe/7/ 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. PS我试图将div ID total更改为div class total,然后起作用了,但是它适用于所有行,而不适用于相关行。

You were referencing everything with id's. 您正在引用带有ID的所有内容。

    $(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/ https://jsfiddle.net/w5qz5exe/12/

Your problem is the fact that the inputs are using id's instead of something else. 您的问题是输入正在使用id代替其他东西。 When looking for the item in question the search stops on the first Id found. 查找有问题的项目时,搜索将在找到的第一个ID处停止。

This updated fiddle https://jsfiddle.net/w5qz5exe/11/ shows how it could be done with classes. 这个更新的小提琴https://jsfiddle.net/w5qz5exe/11/显示了如何使用类来完成。

        $(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. 除上述内容外,从输入中删除所有Id,并将其更改为类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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