显示的一行总和

问题描述 投票:0回答:1

我已经计算了每一行的总数,并试图计算每一行的总数,但是仅显示数量已更改的行。如何计算每一行的总数? jQuery版本是2.2.4。

<tr class="cartoon">
    <td class="col-sm-1 col-md-1 quantity"  style="text-align: center">
        <input type="number" class="form-control fname"   value="1" min="1" label="">
    </td>
    <td class="col-sm-1 col-md-1 text-center pr-01 price" ><strong></strong>
        <input type="hidden" class="form-control artprice"  value="1" label="">
    </td>
    <td class="col-sm-1 col-md-1 text-center pr-01 total" ><strong></strong>
        <input type="hidden" class="form-control total" name = "cart" value="" label="">
    </td>
    <td class="col-sm-1 col-md-1">
        <div class="product" data-id = "key" >
        <button type="button" class="btn btn-danger remove-from-cart" >
            Remove
        </button>
        </div>
    </td>
</tr>

<tr>
    <td></td>
    <td > <h3  style="color: white;" id="cart-total">Total</h3></td>
    <td></td>
    <td>  <div class="text-right final" ><strong>14.5$ </strong></div></td>
    <td></td>
</tr>

Javascript:

jQuery($ => {
    $('.fname').on('change', function() {
        let total = 0;
        let final = 0;
        let $row = $(this).closest('tr');
        let price = $row.find(".artprice").val();
        $row.find('.total strong').text( (this.value * price).toFixed(2)+ '$' );
        $('tr').each(function(){
            total = total + parseFloat($('.artprice').val())*parseFloat($('.fname').val());
        });
        $('.final strong').text(total + '$');
    });
});
jquery
1个回答
0
投票

我想您有几行,每行都有一个<input class="artprice" ...>

在JS的最后一部分中,您要汇总总计:

$('tr').each(function(){
    // ...

您使用选择器$('.artprice')。但是请考虑一下-其中不止一个。那么,该选择器实际上匹配什么?他们都是。 $('.artprice').val()只会为您提供页面上第一个值。那不是您想要的-您确实想要您正在处理的tr中的值。

$('.fname').val()的相同问题-<input class="fname" ...>有多个,这将只为您提供第一个的值。

您需要对这个求和部分应用与最初的fname部分相同的逻辑。

$('tr').each(function(){
    $row = $(this);
    price = parseFloat($row.find('.artprice').val());
    fname = parseFloat($row.finnd('.fname').val());
    total = total + price * fname;
});
$('.final strong').text(total + '$');
© www.soinside.com 2019 - 2024. All rights reserved.