SergioNeves
SergioNeves

Reputation: 99

jQuery Datatables Reload

I'm facing an issue using the Datatables plug-in regarding a table reload after the user adds a row.

I'm receiving some JSON data as part of a webservice call, after successfully receiving that data, I am calling a function that will build the table rows and append them to the tbody of the datatable as follows:

const buildTableRows = obj => {
  const table = document.querySelector('#participantes tbody');
  table.innerHTML = "";
  for (item of obj) {
    const tableRow = `<tr id="${item.ContactoId}" data-contributos="${item.Contributos}" data-updated="false" class="participante-row"><td><i class="material-icons">arrow_right</i>${item.Nome}</td><td class="contributos"><input value="${item.Contributos}">&nbsp&nbsp&nbsp<i class="material-icons delete">delete_forever</i></td></tr>`;
    table.insertAdjacentHTML('beforeend', tableRow);
  }
}

After this, I call another function responsible for initializing the Datatable and saving it to a global object for future reference:

const buildDataTable = () => {
  const table = $('#participantes').DataTable({
    "pagingType": "simple_numbers",
    "pageLength": 4,
    "lengthChange": false,
    "columnDefs": [{
      "targets": 1,
      "orderable": false
    }],

    responsive: true
  });

  controlObj.datatable = table;
}

In my HTML I have a dynamically generated select element which lets the user add a row to the table. When the user adds the row, those two functions get called again. I can see the new row in my data structure but the table doesn't get refreshed without a page reload. I went through the plugin docs and tried to use the destroy method, rows.add(), clear(), draw() etc.. but nothing seems to work for me. The table structure is already in the DOM, I just need to reload the table. Any help would be much appreciated

Upvotes: 0

Views: 2991

Answers (2)

Negi Rox
Negi Rox

Reputation: 3922

Yes you can use DataTable api. without destroying table you just need a function.

$(document).ready(function() {
  var dt = $('#example').DataTable();
  $('#addRow').click(function () {
    var rowHtml = $("#newRow").find("tr")[0].outerHTML
    console.log(rowHtml);
    dt.row.add($(rowHtml)).draw();
  });

});

here is working example

Upvotes: 0

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Datatable cannot be clear and redraw for updated HTML DOM for table but it has to be inserted using JSON array. To refresh it after change in DOM, you need to destroy the table and re-initalize it.

See below example where on click of ADD button I have added new row and reiniitalized the table but before that I have destroyed it.

$(document).ready(function() {
	//Initialize the table and save it in a variable.
  var table = $('#example').DataTable();
  
  var id = 0;
  
  $('#add').on('click', function(){
     table.destroy();
     //add row to the table 
     var html = '<tr><td>' + id + '</td><td>First Name' + id + '</td><td>Last Name' + id + '</td></tr>';
     //console.log(html);
     
     $('#example tbody').append(html);
     id++;
     table = $('#example').DataTable();
  });
} );
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/dataTables.jqueryui.min.css">
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" language="javascript" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
  
  <table id="example" class="display nowrap" style="width:100%">
		<thead>
			<tr>
		 	 <th>ID</th>
			 <th>First name</th>
			 <th>Last name</th>
			</tr>
			</thead>
     <tbody>
      <tr>
        <td>00</td>
        <td>First</td>
         <td>Last</td>
       </tr>
     </tbody>
				</table>
  Click Button to Add row : <input id="add" value="  ADD " type="button">

Upvotes: 1

Related Questions