Multiply two columns with datatables

Asked

Viewed 118 times

1

I intend to multiply two columns with datatables. I have my table this way:

<table border="5" class="teste1" method="POST" id="table">
<thead>
<tr>
<th class="filter" style="width:42px; text-align: center; font-size: 12px">Quantidade</th>
<th class="filter" style="width:25px; text-align: center; font-size: 12px">Preço</th>
</tr>
</thead>
<tbody>
<tr>
<?php
    while($rows_cursos = mysqli_fetch_array($resultado_cursos)) {
?>
<td style="font-size: 12px"> <?php echo $rows_cursos['Quantidade']; ?></td>
<td style="font-size: 12px"> <?php echo $rows_cursos['Preco']; ?></td>
</tr>
<?php } ?>
</tbody>';
<?php
}
?>
</table>

Then I’m trying to multiply the column of quantidade * preço as follows:

(function ($) {$(document).ready(function () {
$('#table').dataTable({  
drawCallback: function () {
  var api = this.api();
  $( api.table().footer() ).html(
    api.column( 1 * 2 ).data().sum()
  );
}
});
})(jQuery)

But it’s not working, and I want to show the data in a row at the bottom of the table, at <tfoot></tfoot> table. I intend that the sum of this multiplication always returns the result according to the filter I do in the table with the datatables

1 answer

1

I solved the problem this way:

Defeni in the column where I want to show the result inside the <tfoot></tfoot>:

<tfoot>
<tr>
<td colspan="9" align="Right">Valor Total: <span id="sumproduct"></span>€</td>
</tr>
</tfoot>

Then in the js I did it this way:

$('#table').dataTable({  
  footerCallback: function(){
   const sumProduct = this
      .api()
      .rows({search:'applied'})
      .data()
      .toArray()
      .reduce((res,row) => {const Quantidade = row[4], Preco = row[8]; return res += Quantidade*Preco},0);
    $('#sumproduct').text(sumProduct);
    }
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.