I have a very similar question to this one.
I create a datatable, then the user can use the search function, click a button and the selected data will then be sent to another function where it is further processed. Initializing the table works fine, also sending the selected data works as intended. However, I fail to access the column names correctly.
That's the datatables version I use:
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js" type="text/javascript"></script>
A bit of background:
By clicking on a link (#calculate
), a table is created and the column headers look fine, e.g. like this:
The user can then select entries (here 88
), and the filtered data are then sent back using a second link (#send_data
). The data used to initialize the column headers look like this (taken from console.log(data.columns);
):
[…]
0: Object { name: "C1", title: "C1", sName: "C1", … }
1: Object { name: "C2", title: "C2", sName: "C2", … }
length: 2
__proto__: Array []
and I can also access table.columns()
, however, when I try table.columns().names()
or table.columns().title()
I receive
TypeError: table.columns(...).names is not a function.
How can I access and pass the displayed column headers i.e. what goes to col_names
in the code below?
The relevant code looks as follows:
<script type="text/javascript">
$(document).ready(function() {
var table = null;
$('#calculate').bind('click', function() {
$.getJSON('/_get_table', {
a: $('#a').val(),
b: $('#b').val()
}, function(data) {
console.log(data.columns);
$("#elements").text(data.number_elements);
if (table !== null) {
table.destroy();
table = null;
$("#a_nice_table").empty();
}
table = $("#a_nice_table").DataTable({
data: data.my_table,
columns: data.columns
});
});
return false;
});
$('#send_data').bind('click', function() {
//console.log(table.columns());
//console.log(table.columns().title());
//console.log(table.columns().names());
$.getJSON('/_selected_data', {
sel_data: JSON.stringify(table.rows( { filter : 'applied'} ).data().toArray()),
col_names: //what goes here?
}, function(data) {
alert('This worked')
});
return false;
});
});
</script>
Here is a possible solution:
table.columns().header().toArray().map(x => x.innerText)
I used the API docs from DataTable. Replacing innerText
with innerHTML
also works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With