0

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();
  });
});
2
  • 1
    Why not use .clone().appendTo()? Edit: oh - DataTable might need to reinit the html dom... Anyway - jsfiddle or code snippet would be helpful EDIT2 - oh my bad. there is jsfiddle Commented Feb 27, 2017 at 12:51
  • thanks Adam can you provide a jsfiddle? thank you Commented Feb 27, 2017 at 12:52

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

That is mainly ref problem. When you set global scope var dt outside and before $(document).ready(); then you'll have no problem accessing it inside.
You are right but dt is also being destroy in the same scope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.