JQuery: add values with condition

0

How could the sum be by state? I have 3 states, "PAID", "MUST" and "CANCELED". Currently I have the totalized general.

Code to add.

var sum=0;
$('.subtotal').each(function() {  
 sum += parseFloat($(this).text().replace(/,/g, ''), 10);  
}); 
$('#resultado_total').val(sum.toFixed(2));

view:

Expected result;

  • Global Total (It's already done)
  • Total Paid
  • Total Must
  • Total Annulled

gracis in advance!

    
asked by JBAL27 01.07.2018 в 00:47
source

1 answer

0

First we create an object with the types you need:

const tipo = { tipo1: 'PAGADO', tipo2: 'ANULADO', tipo3: 'DEBE' };

Here is an example to assign a class to all the rows of your table that contain the word "PAID" which in our case is type1 of our object.

$("#tablon-ed-edd-yeddy").find('tr:contains("' + tipo.tipo1 + '")')
             .attr('class', tipo.tipo1);

Then we simply search and add the rows that contain the class that we assigned previously.

var sumPagado = 0;
$('.PAGADO').each(function(){
  sumPagado += parseFloat($(this).closest("tr").find(':eq(1)').text().replace(',', '.'));
});

Then you can insert that value where you want:).

$('#sumPagado').text(sumPagado.toFixed(2));

This way you can do with the other types.

I leave the example working:

const tipo = { tipo1: 'PAGADO', tipo2: 'ANULADO', tipo3: 'DEBE' };

$("#tablon-ed-edd-yeddy").find('tr:contains("' + tipo.tipo1 + '")')
             .attr('class', tipo.tipo1);

var sumPagado = 0;
$('.PAGADO').each(function(){
  sumPagado += parseFloat($(this).closest("tr").find(':eq(1)').text().replace(',', '.'));
});

$('#sumPagado').text(sumPagado.toFixed(2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="tablon-ed-edd-yeddy">
  <thead>
    <th>Estado</th>
    <th>Total</th>
  </thead>
  <tbody>
    <tr>
      <td>PAGADO</td>
      <td>150</td>
    </tr>
    <tr>
      <td>PAGADO</td>
      <td>250</td>
    </tr>
    <tr>
      <td>ANULADO</td>
      <td>100</td>
    </tr>
    <tr>
      <td>DEBE</td>
      <td>300</td>
    </tr>
    <tr>
      <td>ANULADO</td>
      <td>400</td>
    </tr>
  </tbody>
</table>

<h1>Total Pagado: <span id="sumPagado"></span></h1>
    
answered by 01.07.2018 / 02:58
source