简体   繁体   中英

Appending Rows to a DataTables Grid

I'm trying to add <tr/> tags dynamically to a DataTable, but I didn't find actual good documentation on how the "adding TR process" is supposed to work. I have this as my DataTables setup:

$("#Grid").DataTable({
   stateSave: true,
   fixedHeader: true,
   rowReorder: true,
   .
   .
   columnDefs: [
      { orderable: false, className: "seq-cell", targets: 0 },
      { orderable: false, targets: "_all" }
   ]
})
.on("row-reordered", function (e, diff, edit) {
   for (var i = 0; i < diff.length; i++)
   {
       ..
   }
});

I'm getting the definition of the item in the grid from an MVC action method as an HTML string, via a jQuery AJAX statement:

$.ajax({
    type: "post",
    url: "AddItem",
    data: $("#newitemform").find(":input[name]").serialize(),
    success: function (d) {
       var $body = $("#Grid tbody");
       $body.append(d);
    }
});

The "d" parameter is the HTML for a row; I'm appending it to the body. That adds correctly and but doesn't have the row reorder functionality enabled then. What is the proper way to append to a DataTable, then re-enable whatever functionality?

The best option is to use Datatables API's to add rows to the table. As indicated in the previous response you can use either row.add() or rows.add() . The data needs to be in a data structure that matches your Datatables data structure config, ie, arrays or objects.

However it looks like you are receiving HTML structured data and appending directly to the table. In this case Datatables is not aware of the added data. You will need destroy ( destroy() ) the Datatables table, append your data then re-init Datatables. For example:

$.ajax({
    type: "post",
    url: "AddItem",
    data: $("#newitemform").find(":input[name]").serialize(),
    success: function (d) {
       $("#Grid").DataTable().destroy();
       var $body = $("#Grid tbody");
       $body.append(d);

       $("#Grid").DataTable({
       stateSave: true,
       fixedHeader: true,
       rowReorder: true,
       .
       .
       columnDefs: [
          { orderable: false, className: "seq-cell", targets: 0 },
          { orderable: false, targets: "_all" }
       ]
    })

    }
});

Use row.add() API method to add a new row instead of appending to the table body.

If d contains string in the following format <tr>...</tr> , you could just use $("#Grid").DataTable().row.add($(d).get(0)) to add a new row.

For example:

$.ajax({
    type: "post",
    url: "AddItem",
    data: $("#newitemform").find(":input[name]").serialize(),
    success: function (d) {
       $("#Grid").DataTable().row.add($(d).get(0)).draw();
    }
});

See this example for code and demonstration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM