Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

javascript - Display table by merging two columns into one in HTML/CSS + JS (Datatables)

I use https://datatables.net/ to render sortable and searchable tables on my webservice. My table gets very wide, because of many columns. I want to reduce the width by combining related columns into one. The data of two cells of the same row shall be displayed in a single cell with a linebreak.

I want to transform this:

A B C
D E F
G H J

to this:

A B
... C
D E
... F
G H
... J

Here is my JS example

<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 this example I use the "render" function for rendering two data columns into one. The problem is, that the sorting will be done over the full/concatenated/rendered string. I still want to sort by both "absolute" and "relative" columns. The header of the table shall have two "sort"-buttons for that "combined" column.

Is there some html/css trick with hiding or colspan or whatever to achieve my goal? I googled a lot and it seems like I have to write everything on my own in JS. I could not find anything for me. However, there are so many webpages with this feature of merged columns to one just for displaying.

Here is an example of a table from comdirect bank. Here you can sort in one column two or three different values. This is exactly what I want


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

So, I did not find an easy way to solve my problem... I had to program javascript by myself. Here is my solution: github repository for my 'boss table'

Probably it is also possible to write some plugins for datatable, but I have no idea how this works. I am also a javascript-noob... So it was easier to write it on my own.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...