user1392897
user1392897

Reputation: 851

Modify DataTables Button Action

I want to add the search keyword to the URL of a custom button action element in order to pass the keyword as a GET parameter.

I am initializing the data table like so:

var table = $('#list').DataTable( {
        dom: 'lBfrtip',
    buttons: [
        {
             text: 'Export to PDF',
             className: 'export-to-pdf',
             action: function ( e, dt, button, config ) {
                 window.open('generate_pdf.php?case_id=<?= $case_id? ?>','_blank');
      }

And attempting to append the keyword to the URL using:

// append keyword search values to pdf url
$('#list').on('search.dt', function() {
    var keyword = $('.dataTables_filter input').val();
    //FAILS HERE
    var export_pdf_url = $(".export-to-pdf").attr("href");
    // remove keywords if they already exist
    removeURLParameter(export_pdf_url, 'keyword');
    // append filter value to filtered pdf href
    $(".export-to-pdf").attr("href", export_pdf_url + '&keyword='+keyword);
}); 

This seems to be failing because the action function is not actually assigning the the button a href attribute.

Any suggestions on how to dynamically modify the action function or other approaches would be very much appreciated.

Upvotes: 2

Views: 1507

Answers (1)

Gyrocode.com
Gyrocode.com

Reputation: 58880

Use search() API method which returns currently applied global search when called without arguments.

Then generate URL directly in the callback function for action option.

For example:

buttons: [
   {
      text: 'Export to PDF',
      className: 'export-to-pdf',
      action: function ( e, dt, button, config ) {
         var query = dt.search();
         window.open('generate_pdf.php?case_id=<?= $case_id? ?>&keyword=' + encodeURIComponent(query), '_blank');
      }
   }
],

Upvotes: 1

Related Questions