Adding rows to datatable through javascript

38,099

Solution 1

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>

Solution 2

From the API, this is one of the ways to add rows:

var dataTable = $('#dataTables-example').DataTable();
dataTable.row.add(['1','1','1' ]).draw();

Demo@Fiddle

Share:
38,099
ATP
Author by

ATP

Updated on July 17, 2022

Comments

  • ATP
    ATP almost 2 years

    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 add. Any help is appreciated..

    $('#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>