Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

move rows between two datatables

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!

like image 302
Chrishow Avatar asked Nov 15 '13 14:11

Chrishow


2 Answers

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/

like image 114
davidkonrad Avatar answered Oct 25 '22 14:10

davidkonrad


if table rows has custom css styles you can use row().node instead row().data() to copy classes and other attributes

         btpick.click(function() {
            table1.rows({
                selected: true
            }).every(function() {
                table2.row.add(this.node());
            }).remove();
            table1.draw();
            table2.draw();
         });

and here a function to move all rows

         btpickall.click(function() {
            tqable2.rows.add(table1.rows().nodes()).draw();
            table1.clear();
         });
like image 44
SK.02 Avatar answered Oct 25 '22 15:10

SK.02