Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add dynamic value in "data-row-num" by Jquery

I want to add (data-row-num="1",data-row-num="2",data-row-num="3") for my HTML table row.
Can someone please help me to do it like ?

<table id="example" class="table table-striped first-table" style="width:100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
        </tr>
           <tr>
            <td>Cedric Kelly</td>
            <td>Senior Javascript Developer</td>
            <td>Edinburgh</td>
        </tr>
        
      </tbody></table>
<script type="text/javascript">
$(document).ready(function() {
        $('#example').dataTable( {  } );
} );

  $("tr").each(function() {
      $("tr").attr("data-row-num",????); 
}); 
<script>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Create a counter variable with value 1.

Loop over tbody tr.

Add the counter value as data-row-num and increase the counter value inside the loop.

So you need to modify your code like below:

var counter = 1;

 $("tbody tr").each(function() {
   $(this).attr("data-row-num",counter);
   counter++;
}); 

Working snippet:

$(function() {
  let table = new DataTable('#example');
  var counter = 1;
  $("tbody tr").each(function() {
    $(this).attr("data-row-num", counter);
    counter++;
  });
});
<link rel="stylesheet" href="https://cdn.datatables.net/2.0.7/css/dataTables.dataTables.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/2.0.7/js/dataTables.min.js"></script>
<table id="example" class="table table-striped first-table" style="width:100%">
  <thead>
    <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Tiger Nixon</td>
      <td>System Architect</td>
      <td>Edinburgh</td>
    </tr>
    <tr>
      <td>Cedric Kelly</td>
      <td>Senior Javascript Developer</td>
      <td>Edinburgh</td>
    </tr>

  </tbody>
</table>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading