Reputation: 401
var clientTable = $("#table").DataTable();
clientTable.row.add([1,1,1,1]).draw(false);
I add new row in my datatable with this code but I need to add row in first position of the table.
How can I do this ?
Upvotes: 2
Views: 11056
Reputation: 1
Actualy, is not possible with DataTable default function.
Do it with jQuery :
$('#tableName tr:first').after("<tr role="row"><td></td><td>Your Row</td></tr>");
Upvotes: 0
Reputation: 37
According to the documentation "The rows that are added are subjected to the ordering and search criteria that are applied to the table, which will determine the new row's position and visibility in the table" - so, the new row's position in the table is dependent on the data. If you apply a sort ordering to the table, the new row may be added first - depending on the data. If you don't have a column that would fit for that, you can add a hidden column with a counter and sort by that (see the below snippet for example).
Alternately, you can consider using the RowReorder extension
$(document).ready(function() {
var t = $('#example').dataTable( {
'columns': [
{'title': 'id', 'visible': false},
{'title': 'data'}
],
'order' : [[1,'desc']]
} );
var counter = 1;
$('#addRow').on( 'click', function () {
t.api().row.add( [
counter,
'data for id: ' + counter
] ).draw( false );
counter++;
} );
// Automatically add a first row of data
$('#addRow').click();
} );
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.16/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script>
</head>
<button id="addRow">Add New Row</button>
<table id="example" class="display" width="100%" cellspacing="0" />
</html>
Upvotes: 1