Steve Clarke Steve Clarke - 3 years ago 96
jQuery Question

jQuery loop through table cells

I have a table with id=main... looking to add two cells from each row together, then do the same for another row etc etc. however, while I've managed to do so for the first row, all the result cells are the same in the following rows. e.g., 'test' = 102.9 for all cells int he table... btw, been looking into

.each()
but am unsure how to implement..

<tr id='main'>
<td class='rtng'>100</td>
<td class='win'>2.90</td>
<td class='test'></td></tr>

<tr id='main'>
<td class='rtng'>95</td>
<td class='win'>4.25</td>
<td class='test'></td></tr>


here's my jQuery

$(document).ready(function() {
var num1 = $(".rtng").html();
var num2 = $(".win").html();
var result = parseFloat(num1) + parseFloat(num2);
$(".test").html(result);
});​


another attempt

$(document).ready(function() {
$('tr.rtng').each(function() {
var num1 = $(".rtng").html();
var num2 = $(".win").html();
var result = parseFloat(num1) + parseFloat(num2);
$(".test").html(result);
});
});​


any help would be lovely :)

Answer Source

You can select all the .test elements and set their contents by calling .html() and passing in a function that calculates the correct value:

$(".test").html(function () {
    // `this` refers to the current `.test` element...
    var num1 = parseFloat($(this).siblings(".rtng").html()),
        num2 = parseFloat($(this).siblings(".win").html());
    return num1 + num2;
});​​​​​

Here's a working example.

Side note: as mentioned by others, the values of id attributes must be unique in a document.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download