Reputation: 31
I have an HTML data table, I attached code and also attached test case. Here I do dynamically prepend the row in data table,that means I want to add a row in first position with serial number dynamically. Test Case Datatable
<!DOCTYPE html>
<html>
<head>
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/colreorder/1.5.2/css/colReorder.dataTables.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/colreorder/1.5.2/js/dataTables.colReorder.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.2/js/buttons.colVis.min.js"></script>
<meta charset=utf-8 />
<title>DataTables - JS Bin</title>
</head>
<body>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>S.No</th>
<th>Name</th>
<th>Age</th>
<th>Salary.</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Tiger Nixon</td>
<td>61</td>
<td>$320,800</td>
</tr>
<tr>
<td>2</td>
<td>Garrett Winters</td>
<td>63</td>
<td>$170,750</td>
</tr>
</tbody>
</table>
<input type="button" value="addNew Row" onclick="addNewRow()"/>
</body>
</html>
And the JavaScript is:
function addNewRow() {
var table = $('#example').dataTable();
var rowLen = table.fnGetData().length;
var srNo = rowLen + 1;
var t = $('#example').DataTable();
t.row.add(['1','vuyv','54','89855']).node().id = 'lclSsrContainer_' + rowLen;
t.draw(false);
$('#lclSsrContainer_' + rowLen).attr('style', 'color: #0822f3;');
}
How to add dynamically in first position with dynamic serial number, and no change in data table?
Upvotes: 1
Views: 526
Reputation: 88
Datatable has no property liked
prepend()
If we want to add a row in first postion it collapse our datatable functionalities,So finally after adding a row
t.row.add([rowLen,'vuyv','54','89855']).node().id = 'demo_' + rowLen;
just reorder the table as like
$('.sorting_asc').click();
this jquery function can solve my problem.It comes first position
Upvotes: 2
Reputation: 2214
because your table is set to sort on "s.no" the row will be inserted based in this value so if you did :
t.row.add(['0','vuyv','54','89855']).node().id = 'lclSsrContainer_' + rowLen;
that would be placed in the first row because the "s.no" value is "0" and if you wanted it at the end row every time:
t.row.add([rowLen,'vuyv','54','89855']).node().id = 'lclSsrContainer_' + rowLen;
the problem is though is if you waned "s.no" as any value and still be the first row you would have to remove the sort from the table
hope this helps
Upvotes: 1