Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export only visible tr table to excel with jQuery

Tags:

html

jquery

I have some table combine with this plugin https://github.com/btechco/btechco_excelexport to export data to excel. And then i control the table with checkbox to show or hide specific column of table like this.

But, how to i can export to excel only visible tr table ?

Table.

<div>
<input type="checkbox" value="blabla" checked="checked">Column 1
<input type="checkbox" value="blabla" checked="checked">Column 2
<input type="checkbox" value="blabla" checked="checked">Column 3
</div>

<button id="btnExport">Export</button>
<table id="tableexport">
  <thead>
    <tr>
      <th>No.</th>
      <th>Name</th>
      <th>Phone</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>1</td>
      <td>John</td>
      <td>123456</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Anne</td>
      <td>987654</td>
    </tr>
    <tr>
      <td>3</td>
      <td>Nikki</td>
      <td>786578</td>
    </tr>
  </tbody>
<table>

Hide and Show tr table

$(document).on('change', 'div input', function() {
        var checked = $(this).is(":checked");

        var index = $(this).parent().index();
            $('table thead tr ').each(function() {
                if(checked) {
                    $(this).find("th").eq(index).show();
                } else {
                    $(this).find("th").eq(index).hide(); 
                }
            });

            $('table tbody tr ').each(function() {
                if(checked) {
                    $(this).find("td").eq(index).show();
                } else {
                    $(this).find("td").eq(index).hide(); 
                }
            });
    });

And this code to export table to excel. (Plugin)

$(document).ready(function() {
        $("#btnExport").click(function () {
                $("#tableexport").btechco_excelexport({
                    containerid: "tableexport"
                   , datatype: $datatype.Table
                });
            });
    });
like image 284
user3089464 Avatar asked Nov 21 '25 03:11

user3089464


1 Answers

Try this :

$(document).ready(function() {
    $("#btnExport").click(function () {
            $("#tableexport").clone(true, true)
                             .find(':not(:visible)').remove()
                             .end().prop('id', 'customId').btechco_excelexport({
                                 containerid: "customId"
                                , datatype: $datatype.Table
                             });
    });
});

It clone the table and remove everything that is not visible then export that table.

like image 177
Karl-André Gagnon Avatar answered Nov 22 '25 16:11

Karl-André Gagnon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!