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 :
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>