I utilize the DataTables library from https://datatables.net/ to create sortable and searchable tables on my website. However, my table becomes too wide due to the numerous columns it contains. I am looking for a way to condense the width by merging related columns together. The content of two cells within the same row should be shown in a single cell with a line break.
I aim to convert this:
A B C
D E F
G H J
into this:
A B
... C
D E
... F
G H
... J
Below is an example of my JavaScript code:
<script>
var dataSet =
[
{"name": "A", "absolute": 10, "relative": 0.1},
{"name": "B", "absolute": 20, "relative": 0.2},
{"name": "C", "absolute": 11, "relative": -0.1},
{"name": "D", "absolute": 100, "relative": 0.3},
{"name": "E", "absolute": 8, "relative": 0.04},
];
$(document).ready(function ()
{
$("#example").DataTable(
{
data: dataSet,
columns:
[
{ data: "name", title: "Name" },
{ data: "absolute" , title: "Absolute + <br> "Relative", render: function ( data, type, row, meta ) {
return row.absolute + "<br>" + row.relative; }},
],
"columnDefs": [{ targets: 'data-sortable', orderable: false }]
});
});
</script>
<table id="example" class="display" width="100%"></table>
In the provided code snippet, I am using the "render" function to combine two data columns into one. However, the issue arises with sorting, as it currently sorts based on the concatenated string. I am looking for a solution where I can still sort by both the "absolute" and "relative" columns. Ideally, the table header should include separate "sort" buttons for this combined column.
Is there a way, perhaps utilizing HTML/CSS techniques like hiding elements or using colspans, to achieve this goal? I have searched extensively online, but it seems like I may need to custom code this functionality in JavaScript. Despite this, many websites offer the feature of merging columns for display purposes.