Paul85
Paul85

Reputation: 657

export csv file for selected rows from datatable

I have created a datatable using the following examples:

1.Individual column searching

2.File export

And my code is as follows:

 <script type="text/javascript" charset="utf-8">
    $(document).ready(function() {
    // Setup - add a text input to each footer cell
    $('#example tfoot th').each( function () {
        var title = $(this).text();
        $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
    } );

    // DataTable

    var table = $('#example').DataTable({'scrollX':true, 'dom': 'lBfrtip','buttons': ['csv']});

    // Apply the search
    table.columns().every( function () {
        var that = this;

        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );
} );
</script>

This code is working perfectly. Now I want to export only selected rows without changing the datatable structure in example 1. I am not an expert in Jquery. So can anyone can help me please? Also is it possible add checkboxes for selecting rows?

Thanks

Upvotes: 2

Views: 3215

Answers (1)

Paul85
Paul85

Reputation: 657

I have managed to do that by using following code:

    <script type="text/javascript" charset="utf-8">
    $(document).ready(function() {
    // Setup - add a text input to each footer cell
    $('#example tfoot th').each( function () {
        var title = $(this).text();
        $(this).html( '<input type="text" placeholder="Search '+title+'" />' );
    } );

    // DataTable

    var table = $('#example').DataTable({'scrollX':true, 'dom': 'lBfrtip',buttons: [{ extend: 'csv',text: 'CSV all'},{extend: 'csv',text: 'CSV selected',exportOptions: {modifier: {selected: true}}}],select: true});

    // Apply the search
    table.columns().every( function () {
        var that = this;

        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );
    } );
} );
</script>

So I have added new code in my existing script.

buttons: [{ extend: 'csv',text: 'CSV all'},{extend: 'csv',text: 'CSV selected',exportOptions: {modifier: {selected: true}}}],select: true

Upvotes: 1

Related Questions