If we modify your table slightly to structure it conveniently with <thead>
/ <tdata>
/ <tfoot>
the work can be simplified in the following way:
- If the first and second values are numeric (they are not
NaN
) and there is a third column, we calculate the product and show the result in it.
- We accumulate the partial results to show them in the third column of the foot (if any).
PS: Doing the job with or without jQuery is pretty much the same.
Implementation without jQuery:
var total = 0.;
/* Localizamos las filas de datos */
var filas = document.querySelectorAll('table tbody tr');
/* Por cada fila sumamos los datos de la primera y segunda columna */
filas.forEach(function (valor, indice) {
/* Localizamos las celdas de datos */
var celdas = valor.querySelectorAll('td');
/* Si son valores numéricos y existe la tercera columna */
if (
! isNaN(celdas[0].innerText)
&&
! isNaN(celdas[1].innerText)
&&
celdas[2] !== undefined
) {
/* Calculamos el producto, mostramos el resultado y lo agregamos al total */
var suma = parseFloat(celdas[0].innerText) * parseFloat(celdas[1].innerText);
celdas[2].innerText = suma;
total += suma;
}
});
/* Mostramos la salida */
var pie = document.querySelectorAll('table tfoot td');
if (pie[2] !== undefined) {
pie[2].innerText = total;
}
<table border="1">
<thead>
<tr>
<th>Valor1</th>
<th>Valor2</th>
<th>Valor1*valor2</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>6</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>12</td>
</tr>
</tbody>
<tfoot>
<tr>
<td></td>
<td>Suma:</td>
<td>18</td>
</tr>
</tfoot>
</table>
Implementation with jQuery:
var total = 0.;
/* Localizamos las filas de datos */
var filas = $('table tbody tr');
/* Por cada fila sumamos los datos de la primera y segunda columna */
filas.each(function (indice) {
/* Localizamos las celdas de datos */
var celdas = $( this ).find('td');
/* Si son valores numéricos y existe la tercera columna */
if (
! isNaN(celdas[0].innerText)
&&
! isNaN(celdas[1].innerText)
&&
celdas[2] !== undefined
) {
/* Calculamos el producto, mostramos el resultado y lo agregamos al total */
var suma = parseFloat(celdas[0].innerText) * parseFloat(celdas[1].innerText);
celdas[2].innerText = suma;
total += suma;
}
});
/* Mostramos la salida */
var pie = $('table tfoot td');
if (pie[2] !== undefined) {
pie[2].innerText = total;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<table border="1">
<thead>
<tr>
<th>Valor1</th>
<th>Valor2</th>
<th>Valor1*valor2</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>6</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
<td>12</td>
</tr>
</tbody>
<tfoot>
<tr>
<td></td>
<td>Suma:</td>
<td>18</td>
</tr>
</tfoot>
</table>