0

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

1
  • Can you pls put the code where you have invoked clear and draw methods. Typically in such cases DOM doesn't get refreshed without any event so see if you can invoke clear and draw method using on() or delegate (if you are using older version of jquery. Commented Nov 25, 2019 at 13:08

2 Answers 2

1

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">

Sign up to request clarification or add additional context in comments.

2 Comments

Bhushan Kawadkar looking at your answer I figured out what the problem was. My datatable object was saved in my global controlObj variable, so in order to use the destroy method I had to first save it to a variable. So adding one line of code to my Ajax success callback fixed my issue: const table = controlObj.datatable; table.destroy(); Thanks for your help
happy to help you :)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.