Search code examples
javascriptjqueryhtmldatatables

How do you add rows to a datatable through javascript?


I want to add rows to the datatable when the page is displayed using a javascript array. I am trying to figure this out, but the row does not get added.

$('#dataTables-example').DataTable().fnAddData([
  '1', '1', '1'
]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css">

<table class="table table-striped table-bordered table-hover" id="dataTables-example" border="1">
  <thead>
    <tr>
      <th>Host</th>
      <th>Method</th>
      <th>SSL</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>


Solution

  • Your code works fine, but only with version 1.9.x (or earlier) of the plugin.

    $('#dataTables-example').DataTable().fnAddData([
      '1', '1', '1'
    ]);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="//cdn.datatables.net/1.9.4/js/jquery.dataTables.min.js"></script>
    <link rel="stylesheet" href="//cdn.datatables.net/1.9.4/css/jquery.dataTables.min.css">
    
    <table class="table table-striped table-bordered table-hover" id="dataTables-example" border="1">
      <thead>
        <tr>
          <th>Host</th>
          <th>Method</th>
          <th>SSL</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>

    Following the examples on the datatables.net web site for the latest version (1.10.x):

    $('#dataTables-example').DataTable().row.add([
      '1', '1', '1'
    ]).draw();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
    <link rel="stylesheet" href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css">
    
    <table class="table table-striped table-bordered table-hover" id="dataTables-example" border="1">
      <thead>
        <tr>
          <th>Host</th>
          <th>Method</th>
          <th>SSL</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>