Markcce Eros Markcce Eros - 1 month ago 6
jQuery Question

Javascript / jquery adding pagination to td added via jquery append

I have a table which is hidden when the page is loaded and has not data in it.
After the user click a button the table is then populated and finally shown.
Like this:

tr = $('<tr/>');
tr.append("<td>somedata here</td>");
$('#mytable').append(tr);
$('#mytable').show();


and here's the table:

<table id="mytable" class="table table-striped table-bordered" style="display:none">
<thead>
<tr>
<th>Data below</th>
</tr>
</thead>

<tbody>
</tbody>
</table>


My problem is that I've tried plenty of plugins including dataTables and they just don't work.
I need to find either a way to get the plugins to work or find a way of doing pagination that works with the way I'm populating the table.

How can I do this?

Answer

You can use datatable. It will automatically handle pagination

Here is working demo :

$(document).ready(function() {
  $('#example').DataTable();
  var dataTable = $("#example").dataTable().api();
  $("#addRow").click(function() {
    tr = document.createElement("tr");
    tr.innerHTML = "<tr><td>New row </td><td>Test</td><td>45</td></tr>";
    dataTable.row.add(tr);
    dataTable.draw();
  });
});
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>

<table id="example" class="display" width="100%" cellspacing="0">
  <thead>
    <tr>
      <th>Name</th>
      <th>Position</th>
      <th>34</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Age</th>
    </tr>
  </tfoot>
  <tbody>
    <tr>
      <td>Tiger</td>
      <td>System Architect</td>
      <td>61</td>
    </tr>
    <tr>
      <td>John deo</td>
      <td>System Architect</td>
      <td>61</td>
    </tr>
    <tr>
      <td>Jane Deo</td>
      <td>System Architect</td>
      <td>61</td>
    </tr>
  </tbody>
</table>
<button id="addRow">Add Row</button>