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 ?

1

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

That is correct. You could add the row in question to a second header row then it won't be subject to Datatables sorting.
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>");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.