I'm trying to apply dynamic sum on multiple selection in a jQuery Datatables table but I have bugs crashing me. I applied prevAll() to select from the selected row plus all the previous rows, and so far everything is ok, but the sum makes me on all the previous values except the clicked one and if I change the selection by clicking further up or down the row sum goes wrong.
below is my js/jQuery code
$(document).ready(function() {
var t = $('#tableFatture').DataTable();
var sum = 0;
$('#tableFatture tbody').on('click', 'tr', function() {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
sum = eval(sum "-(" t.cell(this, 4).data() ")");
} else {
sum = 0;
$(this).prevAll().addClass('selected');
t.rows('.selected').every(function(rowIdx) {
sum = eval(sum " (" t.row(rowIdx).data()[4] ")");
});
}
$('#totParz').text('Tot. Selezionato: ' sum.toFixed(2));
});
});
I would like it to add the sum from the selected row up and if I change the selection it will update the sum
CodePudding user response:
<div >
<table id="tableFatture" >
<thead >
<tr >
<th >
<span >Numero</span>
</th>
<th >
<span >Data Emissione</span>
</th>
<th >
<span >Totale €</span>
</th>
<th >
<span >Seleziona</span>
</th>
</tr>
</thead>
<tbody >
@php $total = 0; @endphp
@foreach ($res as $f)
<tr>
<td >{{ $f->mpa_CodSap }}</td>
<td >{{ $f->mpa_NumDoc }}</td>
<td>{{ date('d-m-Y', strtotime($f->mpa_DatDoc)) }}</td>
<td > {{ number_format((float) $f->mpa_importo, 2, '.', '') }}@php $total = $f->mpa_importo; @endphp</td>
<td></td>
</tr>
@endforeach
</tbody>
<tfoot>
<tr>
<td></td>
<td></td>
<td></td>
<td><span id="totParz" >Totale:<span></td>
<td>
<a href="#">
<span > Paga Ora </span>
</a>
</td>
</tr>
</tfoot>
</table>
This is my table in html and laravel
CodePudding user response:
the solution. Add input checkbox and modify js code like this.
$(document).ready(function() {
var t = $('#tableFatture').DataTable();
var sum = 0;
$('#tableFatture tbody').on('change', 'input[type="checkbox"]', function() {
var row = $(this).closest('tr');
if (this.checked) {
$(row).prevAll().find("input[type='checkbox']").prop("checked", true);
sum = 0;
$("input:checked").each(function() {
var row = $(this).closest('tr');
sum = parseFloat(t.cell(row, 4).data());
});
} else {
sum -= t.cell(row, 4).data();
}
console.log(sum)
$('#totParz').text('Totale: ' sum.toFixed(2) '€');
});
});