Cris Cris - 6 months ago 64
jQuery Question

Datatables dropdowns issues

I'm using this code trying to implement dropdowns for all columns in jQuery-Datatables like in this example.

var table = $('#myTable').DataTable({
dom: 'lfBrtip',
buttons: [
{
extend: 'copy',
footer: true
},
{
extend: 'csv',
footer: true
},
{
extend: 'excel',
footer: true
},
{
extend: 'pdf',
footer: true
}
],
initComplete: function () {
this.api().columns().every( function () {
var column = this;
var select = $('<select><option value=""></option></select>')
.appendTo( $(column.header()))
.on( 'change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val()
);

column
.search( val ? '^'+val+'$' : '', true, false )
.draw();
} );

column.data().unique().sort().each( function ( d, j ) {
select.append( '<option value="'+d+'">'+d+'</option>' )
} );
} );
.......
}


Imediately there are problems with this as u can see in the pictures:

1. Clicking the dropdowns makes the columns sort and i don't want that.
enter image description here

2. The buttons get inserted in the export.
enter image description here

What am i doing wrong or how can i correct it? Maybe a workaround?




Updated with buttons:[ ]

Answer

I'm not sure if there's a better way to achieve this but the following is what I've came up with.

You may want to look at buttons.exportData() api reference. I've used the format option in order to format the header columns as follows:

var buttonExp = {
  exportOptions: {
    format: {
      header: function ( data, column, row ) {
        return header[column]; //header is the array I used to store header texts
      }
    }
  }
};

You may want to format the data argument to get the text of the header and strip the html but this one looks cleaner. Then you need to store the header texts in an array like this

var header = [];
header.push("Column Header 1");
header.push("Column Header 2");
header.push("Column Header N");

Finally, bind the button to an element on page as follows

new $.fn.dataTable.Buttons( table, {
        "buttons": [$.extend( true, {}, buttonExp, {
        extend: 'excelHtml5'
    })]
});     

table.buttons(0,null).containers().appendTo('.container');

Here is the demo page.

EDIT

The demo you have provided was quite close to solving the export issue. But you were not binding the button to dom. Thus were not able to see the button on page.

I have made a small modification on your button list by replacing

{
    extend: 'excel',
    footer: true
},

with

$.extend(true, {}, buttonExp, {
  extend: 'excelHtml5'
}),

Also, I have removed the following code, since it was no longer needed.

new $.fn.dataTable.Buttons(table, {
    "buttons": [$.extend(true, {}, buttonExp, {
        extend: 'excelHtml5'
    })]
});

Here is the updated version of your demo.