1

In Jquery Datatable I am trying to add rows dynamically. It is adding dynamically but its NOT adding on the top of the table.

Could any one please help me to add rows dynamically on the top of a table using Jquery Datatable.

Here is the Fiddle http://jsfiddle.net/inDiscover/yo83k3z9/

Inline code

<!DOCTYPE html>
<html>
<head>
<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css">
<!-- jQuery -->
<script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-1.7.2.min.js"></script>

<!-- DataTables -->
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
var giCount = 1;

jQuery(document).ready( function () {
    jQuery('#table_id').DataTable();
} );

function fnClickAddRow() {
    jQuery('#table_id').dataTable().fnAddData( [
        giCount+".1",
        giCount+".2",
        ] );

    giCount++;
}


</script>
</head>
<body>
<a onClick="fnClickAddRow()">Add Row</a>
<table id="table_id" class="display">
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
        </tr>
    </thead>
    <tbody>        
    </tbody>
</table>
</body>
</html>
Gyrocode.com
  • 57,606
  • 14
  • 150
  • 185
user3742125
  • 617
  • 2
  • 9
  • 31
  • To get an idea of how to insert a row at a certain index, as position #1, see this -> http://stackoverflow.com/questions/30712227/datatables-row-add-to-specific-index – davidkonrad Nov 05 '15 at 09:35

1 Answers1

0

The order is set by the first column. By default it sorts ascending, hence it appears that new content is appended to the bottom of the table. If you change the sort order to descending it will work as you require:

jQuery('#table_id').DataTable({
    "order": [[ 0, "desc" ]]
});

Updated example

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339