Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add multiple rows in datatables jquery

I have used https://datatables.net/reference/api/rows.add%28%29 link working but the data showing the table as [object,object]. How to show the object to string. i have used JSON.stringify(obj) its also not working.

HTML

<table id="exampleTable">
 <thead>
  <tr>
   <th>Year</th>
   <th>Month</th>
   <th>Savings</th>
  </tr>
 </thead>
 <tbody>
   <tr>
    <td>2012</td>
    <td>January</td>
    <td>$100</td>
   </tr>
   <tr>
    <td>2012</td>
    <td>February</td>
    <td>$80</td>
   </tr>
 </table>

JS

$('#addRows').click(); 

var table3 = $('#exampleTable').DataTable(); 

$('#addRows').on( 'click', function () { 
    table3.row.add(
       [ { "Year": "Tiger Nixon", "Month": "System Architect", "Savings": "$3,120" },
         {"Year": "Tiger Nixon", "Month": "System Architect", "Savings": "$3,120" }]
    ).draw(); 
});
like image 760
Krishnakumar Subbaiyan Avatar asked Jul 24 '14 07:07

Krishnakumar Subbaiyan


2 Answers

I created two samples in this FIDDLE.

If you want to use objects in rows add you should add columns in your datatable init:

JS

var table3 = $('#exampleTable').DataTable({
    data:[{ "Year": "2012", "Month": "January", "Savings": "$100" },
      { "Year": "2012", "Month": "February", "Savings": "$80" }],
    columns:[{data: 'Year'},
        {data: "Month"},
        {data: "Savings"}]
}); 

but if you don't want to do this you can use next syntax in rows add:

JS

table4.rows.add(
   [[ "Tiger Nixon", "System Architect","$3,120" ],
     ["Tiger Nixon", "System Architect", "$3,120" ]]
).draw(); 

Look fiddle it's more informative.

like image 92
Baximilian Avatar answered Sep 21 '22 04:09

Baximilian


I came across this problem too - I found the documentation to be less than clear. Their example on https://datatables.net/reference/api/rows.add() does not work when I pass my own dynamically created array of objects.

In order to get it working, you have to specify the columns' names when instantiating DataTables.

In any case, the below is a working solution.

var DataTable = $('#tableName').DataTable({
  iDisplayLength: 15,   // number of rows to display
  columns: [
    { data: 'id' },
    { data: 'name' },
    { data: 'car' },
  ]
});

// assume this is a dynamically created array of objects
var persons = [
  {
    id: 1,
    name: 'John',
    car: 'Mercedes',
  }, 
  {
    id: 2,
    name: 'Dave',
    car: 'BMW',
  }, 
  {
    id: 3,
    name: 'Ken',
    car: 'Jeep',
  },  
];

DataTable.rows.add(persons).draw();
like image 30
puiu Avatar answered Sep 20 '22 04:09

puiu