Khai Khai - 4 months ago 17
Javascript Question

Calculate price for each row

I'm stuck with calculating the price for each row. If I select the quantity field, it will print the same price for both rows.

Here is my demo
https://jsfiddle.net/keyro/fw8t3ehs/2/

Thank you in advance.

Html

<table class="table table-condensed table-hover" id="myTable">
<thead>
<tr>
<th>Product</th>
<th class="text-center">Quantity</th>
<th class="text-right">Price ($)</th>
</tr>
</thead>
<tbody class="body">
<tr data-id="1" data-price="20.00">
<td>Apple ($20)</td>
<td><select class="form-control product_quantities" name="product_quantities[]">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td>
<td class="text-right amount" name="amount[]">0</td>
</tr>
<tr data-id="2" data-price="15.00">
<td>Banana ($15)</td>
<td><select class="form-control product_quantities" name="product_quantities[]">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select></td>
<td class="text-right amount" name="amount[]">0</td>
</tr>
<tr>
<td class="text-right bold">TOTAL</td>
<td class="text-center bold">1</td>
<td class="text-right bold"><b class="total">0</b></td>
</tr>
</tbody>
</table>


Javascript

function totalamount() {
var q = 0;

var rows = document.getElementById('myTable').getElementsByTagName("tbody")[0].getElementsByTagName("tr").length;

for( var i = 0; i < rows; i++ ){
var z = $('.amount').html();
q +=z;
}
$('.total').html(z);
}

$(function () {
$('.body').delegate('.product_quantities','change',function(){
var tr = $(this).parent().parent();
var qty = tr.find('.product_quantities option:selected').attr('value');
var price = tr.data('price');

var total = (price * qty);
$('.amount').html(total);
totalamount()
});
});

Answer

Not sure if this is the result that you want. But I have made the code to sum the two amount columns properly.

Just changed the bottom of totalamount function to this:

for( var i = 0; i < rows; i++ ){
    var z = $('.amount:eq(' + i + ')').html();

    if (!isNaN(z)) {
        q +=Number(z);
    }
}

$('.total').html(q);

And as @mrEthol correctly pointed, this should be fixed as well:

$('.amount').html(total);

to

tr.find('.amount').html(total);

So both calculations will work.

Demo.