move rows between two datatables

2019-02-22 12:18发布

问题:

So here's the thing, I have two datatables side by side and I nedd to add items(rows) from Table A to Table B.

'Before' datatable I was doing all right using append:

function add(num)
{
      ...
      $("#myDiv1 tr#p"+num).appendTo("#myDiv2");
      ...
}

Of course this doesn't work with datatables since does not update the table, and I can't seem to get It working using datatables functions, my code goes like the following but isn't working at all:

function add()
{
       ...
       stockTable = $('#stocktable').dataTable();
       catalogTable = $('#catalogtable').dataTable();
       var trdata = stockTable.fnGetData($(this).closest('tr'));
       stockTable.fnDeleteRow($(this).closest('tr'));
       catalogtable.fnAddData(trdata);
       ...
}

Help appreciated!

回答1:

It is unclear exactly what is not working, but here is a working example :

stockTable.on('click', 'tbody tr' ,function() {
   var $row = $(this);
   var addRow = stockTable.fnGetData(this);
   catalogTable.fnAddData(addRow);
   stockTable.fnDeleteRow($row.index());
});

demo -> http://jsfiddle.net/AgB38/


Update. The above answer was targeting dataTables 1.9.x. Below is the same answer targeting dataTables 1.10.x, using the new API.

stockTable.on('click', 'tbody tr' ,function() {
    var $row = $(this);
    var addRow = stockTable.row($row);
    catalogTable.row.add(addRow.data()).draw();
    addRow.remove().draw();
});

demo -> http://jsfiddle.net/4cf43tv1/