Create a new regular table from visible and filtered rows of DataTable

。_饼干妹妹 提交于 2019-12-11 04:04:43

问题


I have a DataTable with paging, filtering and ColVis plugin (column visibility). By pressing a button, I need to get the visible and filtered data of all pages, and generate a new regular table below with this data (this one without datatables, pager, ...).

I tried with oTable.rows({search:'applied'}).data() to get the rows, but instead of getting only the data of the visible columns, it gets the hidden ones as well. And anyway I don't know how to generate the new table.

Here's a demo

How could I do this?

Thanks in advance


回答1:


My answer is based on @davidkonrad's answer with some modifications:

$('button.print-bt').on('click', function() {               
    var fvData = oTable.rows({ search:'applied', page: 'all' }).data(); 

    $('#main_wrapper').append(
       '<table id="newTable">' +
       '<thead>'+
       '<tr>'+
          $.map(oTable.columns().visible(),
              function(colvisible, colindex){
                 return (colvisible) ? "<th>" + $(oTable.column(colindex).header()).html() + "</th>" : null;
           }).join("") +
       '</tr>'+
       '</thead>'+
       '<tbody>' +
          $.map(fvData, function(rowdata, rowindex){
             return "<tr>" + $.map(oTable.columns().visible(),
                function(colvisible, colindex){
                   return (colvisible) ? "<td>" + $('<div/>').text(rowdata[colindex]).html() + "</td>" : null;
                }).join("") + "</tr>";
          }).join("") +
       '</tbody></table>'
    );
});

My answer may not work with a table having objects as data source and may need to be modified where data is retrieved with rowdata[colindex].

I'm using $('<div/>').text(data).html() trick to encode HTML entities that could be present in the data.

See this JSFiddle for demonstration.




回答2:


oTable.rows({ search:'applied', visible:true }).data(); is not valid. See the docs for rows() selector-modifier.

In order to get filtered visual rows you should use page: 'current', so

var fvData = oTable.rows({ search:'applied', page: 'current' }).data();

...would do the trick. To create a completely new table from scratch, and insert the above filtered visible rows you could add this to your click handler :

$('#main_wrapper').append('<table id="newTable">'+
    '<thead>'+
       '<tr>'+
          '<th>Column 1</th>'+
          '<th>Column 2</th>'+
          '<th>Column 3</th>'+
          '<th>Column 4 (hidden)</th>'+
       '</tr>'+
     '</thead>'+
     '<tbody></tbody></table>');

var newTable = $("#newTable").DataTable();
for (var i=0;i<fvData.length;i++) {
    newTable.row.add(fvData[i]).draw();
}    

forked fiddle -> https://jsfiddle.net/sdz1n1gk/



来源:https://stackoverflow.com/questions/30122177/create-a-new-regular-table-from-visible-and-filtered-rows-of-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!