add-multiple-rows-dynamically-in-jquery-datatableswith-fiddle
http://stackoverflow.com/questions/30276507/add-multiple-rows-dynamically-in-jquery-datatableswith-fiddle
HTML
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<link href="https://datatables.net/download/build/nightly/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://datatables.net/download/build/nightly/jquery.dataTables.js"></script>
<div class="container">
<table id="example" class="display" width="100%">
<thead>
<tr>
<th>SortIndex</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>SortIndex</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
<tbody>
<tr>
<td></td>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$3,120</td>
</tr>
<tr>
<td></td>
<td>Garrett Winters</td>
<td>Director</td>
<td>Edinburgh</td>
<td>63</td>
<td>2011/07/25</td>
<td>$5,300</td>
</tr>
<tr>
<td></td>
<td>Ashton Cox</td>
<td>Technical Author</td>
<td>San Francisco</td>
<td>66</td>
<td>2009/01/12</td>
<td>$4,800</td>
</tr>
<tr>
<td></td>
<td>Cedric Kelly</td>
<td>Javascript Developer</td>
<td>Edinburgh</td>
<td>22</td>
...
CSS
body {
font: 90%/1.45em "Helvetica Neue", HelveticaNeue, Verdana, Arial, Helvetica, sans-serif;
margin: 0;
padding: 0;
color: #333;
background-color: #fff;
}
div.container {
min-width: 980px;
margin: 0 auto;
}
JavaScript
// Ref: https://datatables.net/examples/api/counter_columns.html
$(document).ready(function () {
initDatatable();
// bind row click handler
bindEventHandlers();
});
function initDatatable() {
var table = $('#example').DataTable( {
"columnDefs": [ {
"searchable": false,
"orderable": false,
"targets": 0
} ],
"pageLength": 25
//"order": [[ 1, 'asc' ]]
} );
table.on( 'order.dt search.dt', function () {
table.column(0, {search:'applied', order:'applied'})
.nodes()
.each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();
} // initDatatable
function bindEventHandlers() {
var datatable = $('#example').dataTable();
var tableApi = datatable.api();
var counter = 1;
// use delegated for the newly created rows
$('#example').on( 'click', 'tr', function (e) {
e.preventDefault();
var currentRowIndex = tableApi.row( this ).index();
console.log('currentRowIndex ' + currentRowIndex);
var newRowData = [
"",
'New Name',
'New Position',
'New Office',
26,
'New Date',
'New Salary'];
tableApi.row.add(newRowData);
// move the row into position
var data = datatable.fnGetData();
datatable.fnClearTable(false);
data.splice(currentRowIndex + 1, 0, data.pop());
datatable.fnAddData(data);
tableApi.draw();
}); // tr click
} // bindEventHandlers