First of all, you are using the id
attribute with fixed values in the columns. This in practice, when adding the 2nd line, will create elements with id
repeated, which is not correct. Change them from id
to class
, which will not have this problem.
That said, you can get all the elements of a particular class, in case it could be the liq
class in this example, parse the formatted value (probably if you are using a library with this currencyFormatted
there is another function to do the inverse), and add everything.
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><linkhref="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>