Calculate percentage of total HTML columns with Jquery

1

I have a table that is automatically generated by PHP and manipulated by jquery, but I need to calculate the percentage of the total of each of the number lines, what is the best way to do this?

<div id="tableResults" class="container">
  <table id="table_resultados" class="table table-bordered table-hover">
    <thead class="table-head">
      <tr>
        <th>SEX</th>
        <th class="names">FATAL</th>
        <th class="names">SERIOUS</th>
        <th class="names">OTHERS</th>
        <th class="names">TOTAL</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>WOMAN</td>
        <td class="VitimaFATAL">4</td>
        <td class="SERIOUS">6</td>
        <td class="OTHERS">1</td>
        <td class="Total">11</td>
      </tr>
      <tr>
        <td>MEN</td>
        <td class="FATAL">18</td>
        <td class="SERIOUS">28</td>
        <td class="OTHERS">23</td>
        <td class="Total">69</td>
      </tr>
      <tr>
        <td>UNKNOWN</td>
        <td class="FATAL">3</td>
        <td class="SERIOUS">1679</td>
        <td class="OTHERS">3129</td>
        <td class="Total">4811</td>
      </tr>
      <tr id="Totais">
        <td>TOTAL</td>
        <td id="FATAL">25</td>
        <td id="SERIOUS">1713</td>
        <td id="OTHERS">3153</td>
        <td id="Total">4891</td>
      </tr>
    </tbody>
  </table>
</div>

This table comes from a dynamic search in PHP and MYSQL that generates the values, I already did a function in jQuery to calculate the total

function colSum() {
    var ids = new Array();
    $('#table_resultados .names').each(function (){   
        ids.push($(this).html().replace(/\s/g, ''));
        $('#Totais').append('<td id="' + $(this).html().replace(/\s/g, '') + '"></td>')
    });

    $.each(ids, function (index, value) {
        var sum = 0;
        $('.' + value).each(function () {
            sum += parseInt($(this).html());
        });

        $('#' + value).html(sum);
    });

I need to calculate the percentage of the total of all the columns. In this example I need to insert a column after the FATAL, SERIOUS, OUTHERS call % of the total and with values, eg:

  • the% column of FATAL total would be 36.36 - 26.08 - 0.06 - 0.51
  • the% SERIOUS total column would be 54.54 - 40.57 - 34.89 - 35.02

The account to be made is the value of the column multiplied by 100 divided by the value of the total of the same line as the first line 4 * 100/11

I created HTML to stay pretty much as I need it, I do not know how to dynamically generate it for all lines

<div id="tableResults" class="container">
  <table id="table_resultados" class="table table-bordered table-hover">
    <thead class="table-head">
      <tr>
        <th>SEX</th>
        <th class="names">FATAL</th>
        <th>% do TOTAL</th>
        <th class="names">SERIOUS</th>
        <th class="names">OTHERS</th>
        <th class="names">TOTAL</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>WOMAN</td>
        <td class="VitimaFATAL">4</td>
        <th>36,36</th>
        <td class="SERIOUS">6</td>
        <td class="OTHERS">1</td>
        <td class="Total">11</td>
      </tr>
      <tr>
        <td>MEN</td>
        <td class="FATAL">18</td>
        <th>26,08</th>
        <td class="SERIOUS">28</td>
        <td class="OTHERS">23</td>
        <td class="Total">69</td>
      </tr>
      <tr>
        <td>UNKNOWN</td>
        <td class="FATAL">3</td>
        <th>0,06</th>
        <td class="SERIOUS">1679</td>
        <td class="OTHERS">3129</td>
        <td class="Total">4811</td>
      </tr>
      <tr id="Totais">
        <td>TOTAL</td>
        <td id="FATAL">25</td>
        <th>0,51</th>
        <td id="SERIOUS">1713</td>
        <td id="OTHERS">3153</td>
        <td id="Total">4891</td>
      </tr>
    </tbody>
  </table>
</div>
    
asked by anonymous 25.04.2017 / 16:23

2 answers

2
  

I will add my answer with the premise that its function to add the total value is correct, so I will use the HTML posted in your answer, already with the total as a basis.

I will not use the class name or id's , which would be simpler. I'll do it in a slightly more generic way.

First, I add the percentage column after each column. Together, I've saved the index () column to know its actual position.

var indexs = new Array();
$('table#table_resultados thead tr th.names').each(function() {
  var coluna = $(this); // Salvo a coluna atual
  indexs.push(coluna.index()); //Salvo o Index
  coluna.after('<th>%</th>'); // Insiro a nova coluna
});

After saving the index's and having already entered the columns for the percentages, I go through each row to get the value of the total column. After getting the value of the total column, I walk through the index's faults saved, searching for the value of each column and its percentage.

After having all these data, I just enter the value in the row and specific column.

$('table#table_resultados tbody tr').each(function() {
  var coluna = $(this); //Salvo a coluna
  //console.log(coluna)
  var total = parseFloat(coluna.find('td').last().html()); // Salvo o valor total da linha
  $(indexs).each(function(key, value) { // Percorro os index's salvos
    var row = coluna.find('td').eq(value); // Salvo a linha 
    var valor = parseFloat(row.html()); // Salvo o valor total da linha
    var procentagem = (valor / total) * 100; // Verifico a porgentagem
    row.after('<td>' + procentagem.toFixed(3) + '</td>'); // Adiciono o valor na linha e na coluna porcentagem
  });
});

Below you can see the working example.

var indexs = new Array();
$('table#table_resultados thead tr th.names').each(function() {
  var coluna = $(this); // Salvo a coluna atual
  indexs.push(coluna.index()); //Salvo o Index
  coluna.after('<th>%</th>'); // Insiro a nova coluna
});

$('table#table_resultados tbody tr').each(function() {
  var coluna = $(this); //Salvo a coluna
  var total = parseFloat(coluna.find('td').last().html()); // Salvo o valor total da linha
  $(indexs).each(function(key, value) { // Percorro os index's salvos
    var row = coluna.find('td').eq(value); // Salvo a linha 
    var valor = parseFloat(row.html()); // Salvo o valor total da linha
    var procentagem = (valor / total) * 100; // Verifico a porgentagem
    row.after('<td>' + procentagem.toFixed(3) + '</td>'); // Adiciono o valor na linha e na coluna porcentagem
  });
});
th {
  width: 150px;
  text-align: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="tableResults" class="container">
  <table id="table_resultados" class="table table-bordered table-hover">
    <thead class="table-head">
      <tr>
        <th>SEX</th>
        <th class="names">FATAL</th>
        <th class="names">SERIOUS</th>
        <th class="names">OTHERS</th>
        <th>TOTAL</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>WOMAN</td>
        <td class="FATAL">4</td>
        <td class="SERIOUS">6</td>
        <td class="OTHERS">1</td>
        <td class="Total">11</td>
      </tr>
      <tr>
        <td>MEN</td>
        <td class="FATAL">18</td>
        <td class="SERIOUS">28</td>
        <td class="OTHERS">23</td>
        <td class="Total">69</td>
      </tr>
      <tr>
        <td>UNKNOWN</td>
        <td class="FATAL">3</td>
        <td class="SERIOUS">1679</td>
        <td class="OTHERS">3129</td>
        <td class="Total">4811</td>
      </tr>
      <tr id="Totais">
        <td>TOTAL</td>
        <td id="FATAL">25</td>
        <td id="SERIOUS">1713</td>
        <td id="OTHERS">3153</td>
        <td id="Total">4891</td>
      </tr>
    </tbody>
  </table>
</div>
    
25.04.2017 / 18:43
1
  

At the request of the question author by comment

     

Calculate percentage of total columns with PHP

As I do not have the CSS file I did it in the most trivial way.

$db = new PDO('mysql:host=localhost;dbname=DBname;charset=utf8mb4', 'USUARIO', 'SENHA');


echo "<div align=\"center\" id=\"tableResults\" class=\"container\">
  <table id=\"table_resultados\" width=\"800\" class=\"table table-bordered table-hover\">
    <thead class=\"table-head\">
     <tr>
      <th>SEX</th>
      <th class=\"names\">FATAL</th>
      <th>% do TOTAL</th>
      <th class=\"names\">SERIOUS</th>
      <th>% do TOTAL</th>
      <th class=\"names\">OTHERS</th>
      <th>% do TOTAL</th>
      <th class=\"names\">TOTAL</th>
    </tr>
   </thead>
  <tbody>";

    foreach($db->query('SELECT * FROM NomeTabela') as $row) {

       $nome=$row["nome"];

       if ($nome=="WOMAN"){
            $classe="VitimaFATAL";
        }else{
            $classe="FATAL";
        }

        $fatal=$row["fatal"];
        $serious=$row["serious"];
        $others=$row["others"];
        $total=$row["fatal"]+$row["serious"]+$row["others"];

        echo "<tr>
              <td align=\"center\" width=\"150\">".$row["nome"]."</td>
              <td align=\"center\" width=\"50\" class=\"".$classe."\">".$fatal."</td>
              <th align=\"center\" width=\"150\">".number_format(($fatal*100)/$total,2, '.', '')."</th>
              <td align=\"center\" width=\"50\" class=\"SERIOUS\">".$serious."</td>
              <th align=\"center\" width=\"150\">".number_format(($serious*100)/$total,2, '.', '')."</th>
              <td align=\"center\" width=\"50\" class=\"OTHERS\">".$others."</td>
              <th align=\"center\" width=\"150\">".number_format(($others*100)/$total,2, '.', '')."</th>
              <td align=\"center\" width=\"50\" class=\"Total\">".$total."</td>
              </tr>";
        }


  echo "</tbody>
 </table>
</div>";
    
25.04.2017 / 21:41