kaizer1v kaizer1v - 1 month ago 8
Javascript Question

Jquery DataTable unable to add rows using table.rows.add method

For some very funny reason, I am unable to add multiple rows to a simple table using dataTables. Here is the thing,

I am adding 4 rows to an html table using datatable, specifically using the

table.rows.add
method (link).

Below is the simple html code for it with a sample row already present in it.

<table id="items-table" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th>ID</th>
<th>Item Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>Sample Object</td>
</tr>
</tbody>
</table>


And here is the javascript code for it.

// create a dataTable
var itemsTable = $("#items-table").DataTable({
paging: false,
searching: false
});

// add data as rows. Make sure to call the ```.draw``` method.
itemsTable.rows.add([{
"id": "1",
"item": "Aardvark"
}, {
"id": "2",
"item": "Red Bull"
}, {
"id": "3",
"item": "Jack in the Box"
}, {
"id": "4",
"item": "Chair"
}]).draw();


Error says:


DataTable warning: table id=items-table -Requested unknown parameter
'0' for row 1, column 0. For more information see this error.


Using


  • DataTables 1.10.12

  • jQuery v3.1.1



What is going wrong here?

Answer

You need to specify the columns.

// create a dataTable
var itemsTable = $("#items-table").DataTable({
                  paging: false,
                  searching: false,
                  columns: [{data: 'id'}, {data: 'item'}]
                  });
Comments