How To Iterate Through Table And Sum Values Jquery
Can someone help me with how to iterate through my table and summing the value of quantity * price for each row? Here's my table: Copy
You'd probably want to wrap it all in an on change binding for the input fields so it only runs when they change.
Solution 2:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
function solve() {
var iPrice = 0;
var iQuantity = 0;
var sum = 0;
$('#template_item_table tbody tr').each(function () {
iPrice = parseInt($(this).find('td:eq(1)').text(), 10);
iQuantity = parseInt($(this).find('td:eq(2)').find('.quantity').val(), 10);
sum = sum + (iPrice * iQuantity);
});
$('#sum').text("Sum=" + sum)
}
$('#solveButton').click(function () {
solve();
});
});
</script>
</head>
<body style="width:50%;">
<input type="button" value="Get Sum" id="solveButton" />
<div id="sum" style="color:red;font-weight:bold;"></div>
<table id="template_item_table" class="table table-striped">
<thead>
<tr>
<th>Product Code</th>
<th>Unit Price ($)</th>
<th>Quantity</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>12345</td>
<td>50</td>
<td><input type="text" class="form-control quantity" name="quantity"></td>
<td><button class="btn btn-primary"><a href="/product/{{product_code}}">Item Details</a></button></td>
<td><button class="btn btn-danger">Remove Item</button></td>
</tr>
<tr>
<td>2222</td>
<td>53</td>
<td><input type="text" class="form-control quantity" name="quantity"></td>
<td><button class="btn btn-primary"><a href="/product/{{product_code}}">Item Details</a></button></td>
<td><button class="btn btn-danger">Remove Item</button></td>
</tr>
</tbody>
</table>
</body>
</html>
Solution 3:
Not sure where you expect to put these values but you need to find the 2 input values using find()
and multiply them together
$("#template_item_table tr").each(function() {
var price = +$(this).find('td').eq(1).text() || 0,
qty = +$(this).find('.quantity').val() || 0,
rowTotal = qty*price;
});
If you wanted them appended to each row can add to above
$(this).append('<td>' + rowTotal +'</td>')
If you are looking only for a grand total
var total = 0;
$("#template_item_table tr").each(function() {
var price = +$(this).find('td').eq(1).text()|| 0,
qty = +$(this).find('.quantity').val() || 0,
total += qty*price;
});
alert(total);
Solution 4:
Try this
<script>
jQuery(document).ready(function($)
{
$('.form-control.quantity').change(function(){
ComputeTotal();
});
function ComputeTotal()
{
var i=0;
$("#template_item_table tr").each(function() {
i=i+1;
if(i>1){
var quantity1=$(this).find("td input:text").val();
var price1=$(this).find('td').eq(1).text();
sum = sum + (eval(price1) * eval(quantity1));
}
});
alert(sum);
}
</script>
Post a Comment for "How To Iterate Through Table And Sum Values Jquery"