Home > Back-end >  Counting each [tr] in each [table] but resetting the counter in each [table]
Counting each [tr] in each [table] but resetting the counter in each [table]

Time:10-03

I already have a working script that adds a 'data-count' to every row within each table. However, the counter carries over the count to each table.

I only need to reset the count on each individual table for each row.

$(document).ready( function() { 
 var counter = 0;
 $("table").each(function(e) {
   $(this).find('tbody tr').each(function(e) {
  counter  ;
  var self = $(this);
  self.attr('data-count',  counter);
 });
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
  <tr><td>Line 1</td></tr>
  <tr><td>Line 2</td></tr>
  <tr><td>Line 3</td></tr>
  <tr><td>Line 4</td></tr>
</tbody>
</table>

<table>
<tbody>
  <tr><td>Line 1</td></tr>
  <tr><td>Line 2</td></tr>
  <tr><td>Line 3</td></tr>
  <tr><td>Line 4</td></tr>
</tbody>
</table>

<table>
<tbody>
  <tr><td>Line 1</td></tr>
  <tr><td>Line 2</td></tr>
  <tr><td>Line 3</td></tr>
  <tr><td>Line 4</td></tr>
</tbody>
</table>

<table>
<tbody>
  <tr><td>Line 1</td></tr>
  <tr><td>Line 2</td></tr>
  <tr><td>Line 3</td></tr>
  <tr><td>Line 4</td></tr>
</tbody>
</table>

CodePudding user response:

You just need to declare count before table iteration

$(document).ready( function() { 
 $("table").each(function(e) {
   var counter = 0;
   $(this).find('tbody tr').each(function(e) {
  counter  ;
  var self = $(this);
  self.attr('data-count',  counter);
 });
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
  <tr><td>Line 1</td></tr>
  <tr><td>Line 2</td></tr>
  <tr><td>Line 3</td></tr>
  <tr><td>Line 4</td></tr>
</tbody>
</table>

<table>
<tbody>
  <tr><td>Line 1</td></tr>
  <tr><td>Line 2</td></tr>
  <tr><td>Line 3</td></tr>
  <tr><td>Line 4</td></tr>
</tbody>
</table>

<table>
<tbody>
  <tr><td>Line 1</td></tr>
  <tr><td>Line 2</td></tr>
  <tr><td>Line 3</td></tr>
  <tr><td>Line 4</td></tr>
</tbody>
</table>

<table>
<tbody>
  <tr><td>Line 1</td></tr>
  <tr><td>Line 2</td></tr>
  <tr><td>Line 3</td></tr>
  <tr><td>Line 4</td></tr>
</tbody>
</table>

  • Related