0

This probably simple thing knocked me out today :(

I have table with three columns and n rows. I want to take content of first two cells, sum them and put result in column three: 1+2 = 3

3+4 = 7 etc.

$(document).ready(function() {
  $("table tr").each(function() {
    var col1 = parseInt($("td:first-child").text(), 10);
    var col2 = parseInt($("td:nth-child(2)").text(), 10);
    var sum = col1 + col2;
    
    $("td:nth-child(3)").append("<span>" + sum + "</span>");
    return false;
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <tr>
    <td>1</td>
    <td>2</td>
    <td></td>
  </tr>
  <tr>
    <td>3</td>
    <td>4</td>
    <td></td>
  </tr>
  <tr>
    <td>5</td>
    <td>6</td>
    <td></td>
  </tr>
  <tr>
    <td>7</td>
    <td>8</td>
    <td></td>
  </tr>
</table>

From above sample I get 3825 in all last cells. What I do wrong??

isherwood
  • 58,414
  • 16
  • 114
  • 157
miklo
  • 1
  • 1
    Does this answer your question? https://stackoverflow.com/questions/10434711/how-to-iterate-through-a-table-rows-and-get-the-cell-values-using-jquery/25171001 – isherwood Jun 25 '21 at 13:40

1 Answers1

1

You aren't scoping your cell selectors to the row they're in. Also, don't return inside your loop.

$(document).ready(function() {
  $("table tr").each(function() {
    var col1 = parseInt($(this).find("td:first-child").text(), 10);
    var col2 = parseInt($(this).find("td:nth-child(2)").text(), 10);
    var sum = col1 + col2;

    $(this).find("td:nth-child(3)").append("<span>" + sum + "</span>");
  });
});
td {
  background: #ddd;
  padding: 3px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <tr>
    <td>1</td>
    <td>2</td>
    <td></td>
  </tr>
  <tr>
    <td>3</td>
    <td>4</td>
    <td></td>
  </tr>
  <tr>
    <td>5</td>
    <td>6</td>
    <td></td>
  </tr>
  <tr>
    <td>7</td>
    <td>8</td>
    <td></td>
  </tr>
</table>
isherwood
  • 58,414
  • 16
  • 114
  • 157