raduken
raduken

Reputation: 2129

Jquery Datatables add new row in json table

I am using: jquery.dataTables.js from: https://datatables.net

I amtrying to add a new row in my json table.

I could not get it work any ideas why not?

jsfiddle: http://jsfiddle.net/f7debwj2/17/

html:

<table id="example" class="display" width="100%" cellspacing="0">
  <thead>
    <tr>
      <th>order</th>
      <th>name</th>
      <th>country</th>
    </tr>
  </thead>
</table>

<button id="addRow">Add New Row</button>
<table id="newRow">
  <tbody>
    <tr>
      <td>Line 2
        <input type="hidden" value="2" /> </td>
      <td>DVap
        <input type="hidden" value="DVap" /> </td>
      <td>
        <input type="text" value="22" /> </td>
    </tr>
  </tbody>
</table>

jquery:

$(document).ready(function() {
  var dt = $('#example').dataTable();
  dt.fnDestroy();
});

$(document).ready(function() {
  var url = 'http://www.json-generator.com/api/json/get/clmDuyndua?indent=2';
  var table = $('#example').DataTable({
    ajax: url,
    rowReorder: {
      dataSrc: 'order',
    },
    columns: [{
      data: 'order'
    }, {
      data: 'name'
    }, {
      data: 'place'
    }]
  });
  // add row
  $('#addRow').click(function() {
    //t.row.add( [1,2,3] ).draw();
    var rowHtml = $("#newRow").find("tr")[0].outerHTML
    console.log(rowHtml);
    dt.row.add($(rowHtml)).draw();
  });
});

Upvotes: 0

Views: 1613

Answers (2)

manika
manika

Reputation: 187

Your actual error was Uncaught ReferenceError: dt is not defined

Just change table.row.add($(rowHtml)).draw() instead of dt.row.add($(rowHtml)).draw() inside button click event.

Upvotes: 1

gaetanoM
gaetanoM

Reputation: 42054

Like you can see in the documentation you need to change this line:

dt.row.add($(rowHtml)).draw();

to:

table.row.add($(rowHtml)).draw();

The updated fiddle.

Upvotes: 3

Related Questions