Sum of values conenidos in attributes in a tr

1

I have the doubt that I have this code:

<tr class="ejemplo1" sumaEjemplo="+sumaEjemplo+">

I am passing the values dynamically and I want to make the sum of all the <tr> with that attribute (they will be added in the web page and that attribute contains a numeric value).

Example:

<tr class="ejemplo1 valorNumerico1="+valorNumerico1+">

Here you would have to show the sum of all the values of the attributes that are captured by the Numerical value1.

'<td sumaTotal="+sumaTotal+">'+'</td>'

How can I do it with jQuery?

    
asked by SmithBit 05.12.2016 в 03:25
source

1 answer

1

What you want to do is simple with jQuery, you just have to use the attribute selector [] So what you would do would be:

  • Declare a variable for the total and initialize it to 0
  • Select all tr that have the attribute you want valorNumerico1
  • Add the value of that attribute to the total
  • Select td with attribute sumaTotal
  • Assign the total value to that attribute

Something like this (I do not know what your code is like, so it's something simple):

// Declarar una variable para el total e inicializarla a 0
let total = 0;

// Seleccionar todos los 'tr' que tengan el atributo 'valorNumerico1'
$("tr[valorNumerico1]").each(function() {

  // Añadir el valor de ese atributo al total
  total += parseInt($(this).attr("valorNumerico1"));
});

// Seleccionar el 'td' con atributo 'sumaTotal' y asignarle el valor de total a ese atributo (ya de paso también escribirlo)
$("td[sumaTotal]").attr("sumaTotal", total).text(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<table>
  <tr>
    <th>Concepto</th>
    <th>Valor</th>
  </tr>
  <tr valorNumerico1="12">
    <td>Auto</td>
    <td>12</td>
  </tr>
  <tr valorNumerico1="10">
    <td>Auto</td>
    <td>10</td>
  </tr>
  <tr valorNumerico2="8">
    <td>Auto2</td>
    <td>8</td>
  </tr>
  <tr>
    <td>TOTAL valorNumerico1</td>
    <td sumaTotal=""></td>
  </tr>
</table>
    
answered by 05.12.2016 в 07:26