I am loading a table with the following jquery
function get_sales(customer_id,from_date,to_date){
$.ajax({
type: 'POST',
url: 'ajax/sale_pl.php',
data:{customer_id:customer_id,from_date:from_date,to_date:to_date},
dataType:"json",
success: function(response){ //console.log(response);
for(i=0; i<response.length; i++)
{
$('#tdata').append('<tr>'+
'<td><a href="view_invoice.php?id='+response[i].invoice_id+'">'+response[i].invoice_id+'</a></td>'+
'<td>'+response[i].order_date+'</td>'+
'<td><h6 class="mb-1">'+response[i].product_name+'</h6></td>'+
'<td><h6 class="text-muted">'+response[i].product_code+'</h6></td>'+
'<td>'+response[i].sold_qty+'</td>'+
'<td>'+response[i].buy_price+'</td>'+
'<td>'+response[i].sell_price+'</td>'+
'<td>'+response[i].discount+'</td>'+
'<td>'+response[i].cost_price+'</td>'+
'<td>'+response[i].sold_price+'</td>'+
'<td class="profits">'+response[i].profit+'</td>'
+ '</tr>'
);
}
}
});
}
here is my html code for the table
<table class="table table-hover">
<thead>
<tr>
<th>Invoice id</th>
<th>Invoice Date</th>
<th>Product Name</th>
<th>Product Code</th>
<th>Sale Qty</th>
<th>Buy Price</th>
<th>Sale Price</th>
<th>Discount</th>
<th>Cost Price</th>
<th>Sold Price</th>
<th>Profit</th>
</tr>
</thead>
<tbody id="tdata">
</tbody>
<tfoot>
<tr>
<th colspan='10'>Total Profit</th>
<th id="total_profit">0</th>
</tr>
</tfoot>
</table>
what i am trying is to get the total of the profit column. I have tried the following one
function calcSub(){
var totalProfit= 0;
$(".profits").each(function(){
totalPrice += parseInt($(this).val());
$("#total_profit").html(totalPrice);
});
};
but this is not working.
Please suggest me the solution. I am new to jQuery. Thanks in advance for help.
2
Answers
It might be a typo
need to be
Also you need to set the total value after you finish the iteration,full code listed below:
You need to use .text() not
.val()
..val()
is used when you are getting aninput
value. But in your case its simply getting the.text()
of yourtd
items.Edit: Since the
two
(get_sales
andcalcSub()
) functions are running simultaneously you need to useasync
function on and wait for theawait
for ajax to be completed onsuccess
before proceeding tocalcSub()
for your calculationsAdd this code your file:
Complete Working Demo as per the question