DataTables.js Add/Replace Row

by Kyle Mitofsky

HTML

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.12/css/jquery.dataTables.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.12/js/jquery.dataTables.js"></script>
<table id="example" class="display" cellspacing="0" >
  <thead>
    <tr>
      <th>Hidden</th>
      <th>Name</th>
      <th>Age</th>
      <th>Replace</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Line 1 <input type="hidden" value="1"/> </td>
      <td>Bob    <input type="hidden" value="Bob"/> </td>
      <td><input type="text" value="18"/> </td>
      <td><input type="button" value="Replace" class="replace"/> </td>
    </tr>
  </tbody>
</table>

<br/>
<button id="addRow">Add New Row</button>

<table id="newRow" style="display:none">
  <tbody>
    <tr >
      <td>Line 2 <input type="hidden" value="2"/>   </td>
      <td>Ann    <input type="hidden" value="Ann"/> </td>
      <td><input type="text" value="21"/> </td>
      <td><input type="button" value="Replace" class="replace"/> </td>
    </tr>
  </tbody>
</table>










<!-- Post Info -->
<div style='position:fixed;bottom:0;left:0; background:lightgray;width:100%;'>
    About this SO question:
    <a href='http://stackoverflow.com/a/25081588/1366033'>
        How can I pass a html table row into DataTable.net fnAddData
    </a><br/>
    <a href='http://stackoverflow.com/a/43522442/1366033'>
        How to update an existing row with HTML on an existing JQuery Datatables?
    </a>
</div>

JavaScript

$(function() {
	  // initialize table
    var $dt = $('#example').DataTable({
        paging:   false,
        bFilter: false, 
        bInfo: false
    });
    
 		// add row
    $('#addRow').click(function () {
        //$dt.row.add( [1,2,3] ).draw();
        var newRow = $("#newRow").find("tr")[0].outerHTML
        $dt.row.add($(newRow)).draw();
    });
    
    // replace row
    $('.replace').click(function () {
    		var $row = $(this).closest("tr")
        var newRow = $("#newRow").find("tr")[0].outerHTML
  			
        var newRowDataArray = TrToData(newRow)  
  
        //$row.replaceWith($(newRow))
        //data represents an array of string values that are the innerHTML of each td
        $dt.row($row).data(newRowDataArray).draw();
        
    });
    
    function TrToData(row) {
     	 return $(row).find('td').map(function(i,el) {
        	return el.innerHTML;
       }).get();
    }
 
});