I have a multiple table and I want to get the total per table. Please see the demo in fiddle.
var total = 0;
$("table").each(function(i){
total += +$('.a', this).text() || 0;
console.log( 'total: '+total );
$("#subtotal", this).text( total );
//console.log( '-'+$('.a', this).text() );
});
You need to move var total=0
inside the table loop so it resets for each table
Then you need to loop over each cell to get individual cell's text.
The problem with getting all $('.a', this).text()
is it concatenates all elements text into one string which is why you see numbers like "1357"
as total in first table
Finally you can't repeat ID's in page so change subtotal to a class
$("table").each(function(i) { var total = 0; $('.a', this).each(function() { total += +$(this).text() || 0; }); $(".subtotal", this).text(total); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td class="a">1</td> <td>2</td> </tr> <tr> <td class="a">3</td> <td>4</td> </tr> <tr> <td class="a">5</td> <td>6</td> </tr> <tr> <td class="a">7</td> <td>8</td> </tr> <tr> <td class="subtotal"></td> </tr> </table> <hr> <table> <tr> <td class="a">1</td> <td>2</td> </tr> <tr> <td class="a">3</td> <td>4</td> </tr> <tr> <td class="a">5</td> <td>6</td> </tr> <tr> <td class="a">7</td> <td>8</td> </tr> <tr> <td class="a">9</td> <td>10</td> </tr> <tr> <td class="a">11</td> <td>12</td> </tr> <tr> <td class="subtotal"></td> </tr> </table>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.