raduken
raduken

Reputation: 2119

Jquery Datables delete and add new row

I am using: jquery.dataTables.js from: https://datatables.net

Issue:

If I delete some rows and add a new row after, the rows I deleted come back.

If I add 1 row and delete this one, after I add another row, inserts 2 instead just 1

so what I trying to archive is:

row deleted is deleted not back.

if I add new row added just 1, does not matter if i deleted a row before or not.

html:

<table id="example" class="display" width="100%" cellspacing="0">
  <thead>
    <tr>
      <th>order</th>
      <th>name</th>
      <th>country</th>
      <th>delete</th>
    </tr>
  </thead>
</table>

<button id="addRow">Add New Row</button>
<table id="newRow">
  <tbody>
    <tr>
      <td>Line 2
        <input type="hidden" value="2" /> </td>
      <td>DVap
        <input type="hidden" value="DVap" /> </td>
      <td>
        <input type="text" value="22" /> </td>
      <td>
        <i class="fa fa-minus-square" aria-hidden="true"></i> </td>
    </tr>
  </tbody>
</table>

jquery:

  $(document).ready(function() {
    var dt = $('#example').dataTable();
    dt.fnDestroy();

  });
  $(document).ready(function() {
    var url = 'http://www.json-generator.com/api/json/get/bQzyuEGndu?indent=2';
    var table = $('#example').DataTable({
      ajax: url,
      rowReorder: {
        dataSrc: 'order',
      },
      columns: [{
        data: 'order'
      }, {
        data: 'place'
      }, {
        data: 'name'
      }, {
        data: 'delete'
      }],
      "fnDrawCallback": function(oSettings) {
        $("i.fa.fa-minus-square").click(function(event) {
          $(this).closest("tr").remove();
        });
      }
    });
    // add row
    $('#addRow').click(function() {
      //t.row.add( [1,2,3] ).draw();
      var rowHtml = $("#newRow").find("tr")[0].outerHTML
      console.log(rowHtml);
      table.row.add($(rowHtml)).draw();
    });
  });

jsfiddle: http://jsfiddle.net/5L2qy092/3/

Upvotes: 0

Views: 2019

Answers (1)

Ja9ad335h
Ja9ad335h

Reputation: 5075

you should use DataTables api to remove/delete rows, other wise DataTables cant know whats actually deleted.

also you need to use initComplete instead, since fnDrawCallback fires every time table draws, so you don't want to add click event handler every time

 "initComplete": function(oSettings) {
    $("i.fa.fa-minus-square").click(function(event) {
      table.row( $(this).closest('tr') ).remove().draw();
    });
  }

working JSFIDDLE

EDIT

use jquery delegate click for dynamically added rows

 "initComplete": function(oSettings) {
    $(this).on("click", "i.fa.fa-minus-square", function(event) {
      table.row( $(this).closest('tr') ).remove().draw();
    });
  }

Upvotes: 1

Related Questions