0

I have code that uses datatables. When user first visits the page datatables should be applied. After user ether wants to update or add new data the existing table should be updated. Here is example of my code:

$(document).ready(function() {
  let $items_datatable = $('#tbl-items').DataTable({
    order: [
      [0, "asc"]
    ],
    columnDefs: [{
      targets: 2,
      searchable: true,
      orderable: false,
      visible: true
    }]
  });
});

$('#add-row').on('click', function() {
  let $tbl_row = $('<tr>').prop('id', 'review_row_' + 5);
  $tbl_row.append('<td class="text-center"><button type="button" class="btn btn-dark btn-sm edit" data-riskid="5">Tier 5</button></td>');
  $tbl_row.append('<td>1 Year</td>');
  $tbl_row.append('<td>Very High</td>');
  $items_datatable.row.add($tbl_row).draw();
});
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<button type="button" id="add-row">Add Row</button>
<table class="table table-striped table-bordered" id="tbl-items">
  <thead>
    <tr class="bg-info">
      <th class="text-center">Level</th>
      <th>Period</th>
      <th>Description</th>
    </tr>
  </thead>
  <tbody>
    <tr id="row_1">
      <td class="text-center"><button type="button" class="btn btn-dark btn-sm edit" data-id="1">Tier 1</button></td>
      <td>4 Years</td>
      <td>Low</td>
    </tr>
    <tr id="row_2">
      <td class="text-center"><button type="button" class="btn btn-dark btn-sm edit" data-id="1">Tier 2</button></td>
      <td>3 Years</td>
      <td>Moderate</td>
    </tr>
    <tr id="row_3">
      <td class="text-center"><button type="button" class="btn btn-dark btn-sm edit" data-id="1">Tier 3</button></td>
      <td>2 Years</td>
      <td>Medium</td>
    </tr>
    <tr id="row_4">
      <td class="text-center"><button type="button" class="btn btn-dark btn-sm edit" data-id="1">Tier 4</button></td>
      <td>1 Year</td>
      <td>High</td>
    </tr>
  </tbody>
</table>

I'm getting an error that $items_datatable is not defined. I see that is because my table is defined inside of the document.ready function block. How this issue can be fixed? Is there a better way to define datatable on page load? I still need datatable object to use if I want to modify table records. Also, is the way of adding rows correct? Or there is a better way to do that? What about editing existing data? Thank you.

espresso_coffee
  • 5,980
  • 11
  • 83
  • 193

1 Answers1

0

You have to remove $(document).ready(function() from your code because items_datatable is scopped your code will work fine as far as you set your jquery script and datatables cdn script in the right order The $(document).ready(... from the documentation is only for demonstration it's not required

let $items_datatable = $('#tbl-items').DataTable({
    order: [
      [0, "asc"]
    ],
    columnDefs: [{
      targets: 2,
      searchable: true,
      orderable: false,
      visible: true
    }]
  });
    $('#add-row').on('click', function() {
      let $tbl_row = $('<tr>').prop('id', 'review_row_' + 5);
      $tbl_row.append(`<td class="text-center"><button type="button" class="btn btn-dark btn-sm edit" data-riskid="5">Tier 5</button></td>`);
      $tbl_row.append(`<td>1 Year</td>`);
      $tbl_row.append(`<td>Very High</td>`);
      $items_datatable.row.add($tbl_row).draw();
    });
      </script>
Sven.hig
  • 4,449
  • 2
  • 8
  • 18
  • A page cannot always be manipulated safely by JavaScript until the DOM is ready. It can be risky to remove the `$(document).ready()` function for this reason. See [here](https://stackoverflow.com/questions/9504315/what-exactly-document-ready-means-in-jquery), for a discussion and links. – andrewJames Jun 04 '20 at 12:28
  • To add a row of data to a DataTable object, use the [`row.add()`](https://datatables.net/reference/api/row.add()) function. Otherwise, you have added the row to the DOM using HTML, and it will be displayed to the user. But DataTables does not know about it - and the row will disappear when DataTables re-draws. – andrewJames Jun 04 '20 at 12:37