First of all, you are using the attribute in the columns id
with fixed values. This in practice, when adding the 2nd line, will create elements with id
repeated, which is not correct. Change them from id
for class
, you won’t have that problem.
That being said, you can take all the elements of a certain class, in case it could be the class liq
in this example, parse the formatted value (probably if you are using a library with this function currencyFormatted
, there may be another function to do the reverse), and sum it all up.
See if this example helps you, the function that does what you want called updateSum
:
$(function() {
var nItem = 1;
function newItem(ev) {
console.log('newItem');
var value = getRandomIntInclusive(1000, 10000);
var qty = getRandomIntInclusive(1, 5);
var total = value * qty;
var item = {
'name': 'Item ' + nItem++,
'value': (value / 100).toFixed(2),
'qty': qty,
'total': (qty * total / 100).toFixed(2)
};
var html = '<tr>';
for(var k in item) {
html += '<td class="' + k + '">' + item[k] + '</td>';
}
html += '<td><button class="btn btn-danger btn-xs remove-item"><span class="glyphicon glyphicon-trash" aria-label="Remove Item"></span></button>';
html += '</tr>';
$('table.table-bordered tbody').append(html);
updateSum();
}
function removeItem(ev) {
console.log('removeItem');
$(this).closest('tr').remove();
updateSum();
}
function updateSum() {
console.log('updateSum');
var total = 0;
$('tbody .total').each(function (idx, el) {
total += parseFloat($(el).html());
})
$('#sum').html(total.toFixed(2));
}
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
$("#new-item").on('click', newItem);
$(document).on('click', '.remove-item', removeItem);
});
th.name {
width: 50%;
}
th.value {
width: 15%;
}
th.qty {
width: 15%;
}
th.total {
width: 15%;
}
th.remove-action {
width: 5%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class='container-fluid'>
<button class="btn btn-primary" id="new-item">New item</button>
<hr />
<table class="table table-bordered table-striped table-hover table-condensed">
<thead>
<tr>
<th class='name'>Name</th>
<th class='value'>Value</th>
<th class='qty'>Qty</th>
<th class='total'>Total</th>
<th class='remove-action'>-</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th colspan='3' class='text-right'>Sum</th>
<th id="sum">-</th>
<th> </th>
</tfoot>
</table>
</div>
It would be interesting for you to post what you have already tried to do or what mistake is causing the problem. Get edit the question and enter this information?
– bio