How to call Datatable csv button from custom butto

2019-05-07 02:44发布

问题:

Need to call csv button from my custom button.

<button value="Export report to Excel" class="button-default datatable-csv" type="button" id="ExportReporttoExcel">
                <span>Export report to Excel</span>
            </button>

Instead of calling it from the Datatable button, i want the same functionality from the above button.

Looking for some configuration changes in Datatable so that i can call my custom button to export the table records as csv.

var table=$('#tableId').DataTable( {
    "paging":   true,
    "info":     true,
    "searching": true,      
    ,buttons: true
});


$("#SEARCH").on("keyup search input paste cut", function() {
    table.search(this.value).draw();
});

var buttons = new $.fn.dataTable.Buttons(table, {
     buttons: [
       'csvHtml5'
    ]
}).container().appendTo($('#ExportReporttoExcel'));

Getting output like below but i need only one button.

回答1:

At last i found the solution.

In Datatable configuration , i added click event for the button to be triggered.

buttons: [
        { 
            extend: 'csv',
        }
    ]

$("#ExportReporttoExcel").on("click", function() {
    table.button( '.buttons-csv' ).trigger();
});

This works fine for me thanks for the comments and answers



回答2:

dataTables export buttons is by default enriched with signature classes like .buttons-excel, .buttons-pdf, .buttons-csv and so on. Take advantage of that :

$('#ExportReporttoExcel').on('click', function() {
  $('.buttons-excel').click()
});


回答3:

If you are trying to trigger the click event of another button and you are using jQuery (according to your tags), you can use

<button onclick="$('#ExportReporttoExcel').click()">Click me</button>

This selects the element with the id "ExportReporttoExcel" and triggers a click with using jQuery.