2
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 ?

Kerem Çakır
  • 401
  • 2
  • 7
  • 19
  • 1
    you may take a look to [DataTables row.add to specific index](https://stackoverflow.com/questions/30712227/datatables-row-add-to-specific-index) – gaetanoM Feb 06 '18 at 13:26

2 Answers2

1

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>
Dan
  • 37
  • 8
  • That is correct. You could add the row in question to a second header row then it won't be subject to Datatables sorting. – K Thorngren Feb 06 '18 at 14:44
0

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>");
Saddem
  • 1