How to calculate the total of each row?

2

I need to show the total ( .total ) of each row ( .numero ).

Obviously my problem is the loop that I am doing wrong.

Right now I have the following code:

<table id="tabla" border="1">
  <thead>
    <tr>
      <td>Numero</td>
      <td>total</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="numero">1</td>
      <td class="total"></td>
    </tr>
    <tr>
      <td class="numero">2</td>
      <td class="total"></td>
    </tr>    
  </tbody>
</table>

  $(document).ready(function() 
  {    
    $(document).on('focusout','#factor',function()
    {
      $("#tabla").each(function()
      {
        var factor = $("#factor").val();
        var numero = $("#tabla tbody tr").siblings().text();         
                  var r = parseInt(factor) + parseInt(numero);
                  $(".total").text(r);
                  console.log(r); 
      })    
    })
  });
    
asked by Alex Hunter 09.01.2018 в 13:32
source

1 answer

5

The modifications you need to make are the following:

  • [ Optional ] To give a better user experience, I recommend you use the event input instead of fousout .

  • You must use parseInt to get the value as an integer ( or parseFloat to get the value as a decimal )

  • The elements you must search and iterate are the rows in the table ( eg: $("#tabla tbody tr").each )

  • For each row ( eg: $tr = $(this) ) you should find the cells with the classes .numero and .total ( eg: $tr.find('.numero') )

Example:

$(function() {
  $('#factor').on('input', function() {
    var factor = parseInt($("#factor").val(), 10) || 0;
    
    $("#tabla tbody tr").each(function() {
      var $tr = $(this);
      var numero = parseInt($tr.find('.numero').text(), 10);
      var r = factor + numero;
      
      $tr.find('.total').text(r);
    })
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<table id="tabla" border="1">
  <thead>
    <tr>
      <td>Numero</td>
      <td>total</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="numero">1</td>
      <td class="total"></td>
    </tr>
    <tr>
      <td class="numero">2</td>
      <td class="total"></td>
    </tr>
  </tbody>
</table>

Sumar: <input id="factor" type="number" value="0"/>
    
answered by 09.01.2018 / 13:51
source