Search code examples
jquerydatatable

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

  • Loop over tbody tr using .each()

    Use the function index parameter to provide value to data-row-num. Just take care that the index parameter starts with 0 so you need to add 1 into it each time.

    So you need to modify your code like below:

    $(function() {
      let table = new DataTable('#example');
      $("tbody tr").each(function(i,e) {
        $(this).attr("data-row-num", i+1);
      });
    });
    

    Working snippet:

    $(function() {
      let table = new DataTable('#example');
      $("tbody tr").each(function(i,e) {
        $(this).attr("data-row-num", i+1);
      });
    });
    <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>