Calculate values for each column of an html table

0

I'm wanting to calculate values from a table. Each column has different values, at the end of the table, I would like to enter the total value. Below is my html.

<table class="table table-striped m-table m-table--head-bg-success">
  <thead>
    <tr>
      <th>Nº doc</th>
      <th>Valor doc</th>
      <th>Correção doc</th>
      <th>Multa doc</th>
      <th>Valor extra doc</th>
      <th>Valor Total</th>
    </tr>
  </thead>
  <tbody>
    <?php 
      $sql = $db->prepare("SELECT * FROM doc where cod_doc = '$id_get' ORDER BY data ASC ");          
      $sql->execute();   $a = 0  ;        
           while($row=$sql->fetch(PDO:: FETCH_ASSOC)){ 
              $a++;
        $pct_multa = 2;
        $pct_ext = 1;
        $pct_cob = 10; 
        $valor_doc = $row['valor_doc'];
        $data = $row['data'];     
    ?>
    <tr>
      <th scope="row">
        <? echo $row['numero_doc']?>
      </th>

      <td id="sum1"> 
        <? echo str_replace('.', ',', $valor_doc)?>
      </td>
      <td id="sum2">
        <? echo str_replace('.', ',', $doc_correcao)?>
      </td>
      <td id="sum3">
        <? echo valorMulta($valor_doc,$pct_multa) ?>
      </td>
      <td id="sum4">
        <? echo valorext($valor_doc,$pct_ext) ?>
      </td>
    
      <td id="sum5"><span class="m-widget6__text m--align-right m--font-boldest m--font-brand">
														<? echo valorTotal($valor_doc,$pct_ext,$pct_multa, $data) ?>
													</span></td>
    </tr>
    <?php } ?>
  </tbody>
</table>

I've created an id for every td (Ex: id="sum1") of the total column I want to calculate. How can I proceed? Thank you in advance for your attention.

    
asked by anonymous 11.06.2018 / 04:15

1 answer

1

First, the id attribute is something that should be unique, so instead of id use class :

<tr>
    <th scope="row">
    <? echo $row['numero_doc']?>
    </th>
    <td class="sum1">
        <? echo str_replace('.', ',', $valor_doc)?>
    </td>
    <td class="sum2">
        <? echo str_replace('.', ',', $doc_correcao)?>
    </td>
    <td class="sum3">
        <? echo valorMulta($valor_doc,$pct_multa) ?>
    </td>
    <td class="sum4">
        <? echo valorext($valor_doc,$pct_ext) ?>
    </td>    
    <td class="sum5">
        <span class="m-widget6__text m--align-right m--font-boldest m--font-brand">
            <? echo valorTotal($valor_doc,$pct_ext,$pct_multa, $data) ?>
        </span>
    </td>
</tr>

In% w / w you can repeat the example for each column:

var sum1 = 0;

$.each($('.sum1'),function(){
    var num = parseInt($(this).text().replace(/[^0-9]/g,''));
    sum1 += num;
});
  • Jquery holds only the numbers of the text drawn by .replace(/[^0-9]/g,'') ;

  • text() turns parseInt() into string ;

Then just reform the value for money and include where it will be displayed.

    
11.06.2018 / 14:28