When clicking on a line, the cells are assigned the class="active" , it is necessary to sum the cells in the selected lines.

 <table> <tr> <td>name1</td> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>name2</td> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>name3</td> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td class="total">?</td> <td class="total">?</td> <td class="total">?</td> <td class="total">?</td> </tr> </table> <script> $("tr").click(function() { $(this).children("td").toggleClass("active"); var totals=[0,0,0,0]; $("table").each(function() { $(this).find('.active').each(function(i){ totals[i]+=parseInt( $(this).text()); }); }); $("td.total").each(function(i){ $(this).html(totals[i]); }); }); </script> 

    1 answer 1

    The fact is that you are looking for .active elements for the table and they are numbered with 1, 2, 3, ..., 10, 11, 12. As a result, you have totals not 4 elements, but 12 (3 columns for 4 elements in them).

    You need instead

     $("table").each(function() { 

    Write down

     $("table tr").each(function() { 

    Then you will have numbering within each row of the table.

    • earned, but I did not understand why 9? - YarNik
    • @YarNik Because you count the number of .active elements in a table - there are 9 such elements in a table with 3 elements in each row. When you count the number of elements .active at the line - there are 3 of them in each line. - cheops
    • 4 in line. - YarNik 5:48 pm
    • Yes, correctly, 4 in line, now I will correct the answer. - cheops pm
    • I caught the essence, thanks! knocked down the number 9 =) - YarNik