Combine two columns into a single table column using HTML/CSS and JavaScript with the help of Datatables

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.

Here is an example table from comdirect bank where sorting can be done based on two or three different values within the same column. This is the precise functionality I am seeking

Answer №1

Unfortunately, I couldn't find a simple solution to my issue... I ended up having to write my own javascript code. You can check out the solution in my GitHub repository for my 'boss table'

Perhaps there's a way to create plugins for Datatables, but the process is unknown to me. I'm still a beginner in javascript... So, it was more straightforward for me to create it from scratch.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to retrieve the third party child component within a Vue parent component

Within my example-component, I have integrated a third-party media upload child component called media-uploader: <example-component> <form :action= "something"> // Other input types <media-upload :ref="'cover_up ...

Passing variables with AngularJS and Typescript using a service

Currently in the process of developing an application using AngularJS, I am faced with the challenge of passing a URL when clicking on a menu button in order to utilize that URL within an iframe on another view controlled by a separate controller. Despite ...

Utilizing the combineReducers() function yields disparate runtime outcomes compared to using a single reducer

Trying to set up a basic store using a root reducer and initial state. The root reducer is as follows: import Entity from "../api/Entity"; import { UPDATE_GROUPING } from "../constants/action-types"; import IAction from "../interfaces/IAction"; import IS ...

The spreading of personalized events

I am expecting my CustomEvent to be propagated from the document to all the DOM elements. However, for some unknown reason, it is not happening. Can you point out what mistake I might be making? <html> <script> function onLoad() { var myDi ...

Encountering [object, Object] while attempting to display JSON object retrieved from req.body in the console

While attempting to insert a product's details into my API's PostgreSQL database using Postman, I encountered an issue where the values of the specs key were displayed as [object Object] instead of showing the complete data. As a result, even in ...

Exploring the source code of NPM public and private packages within the node_modules directory

As someone who is new to javascript development, I want to create a private npm package that cannot be accessed by users. However, I have noticed that I can still view the code of other npm packages labeled as closed-source by entering their node_modules s ...

Exploring different sections of the website

I am looking to create a seamless navigation experience between controls on a webpage. Below is an example code snippet that outlines the functionality where a user can click on any component and be directed to another controller. Sample code: const app ...

Error Message: ElectronJS - Attempted to access the 'join' property of an undefined variable

I am currently working on developing a tray-based application. However, I am encountering an error that reads: Uncaught TypeError: Cannot read property 'join' of undefined Can anyone guide me on how to resolve this issue? This is the content ...

React-Native error message: Promise rejection unhandled - React child cannot be an object

I am experiencing an issue with rendering a list from an array of objects that have the structure provided below. While I have successfully handled the promise and set the data to the state, I keep encountering an error specifically with this array. The da ...

React function does not provide a return value

In my function, I am calculating the current sum of elements. Within my Api, there is a method called Getcoin that works correctly when I log each element during the foreach cycle. However, I am not getting any results in the return statement or console.lo ...

Node.js and socket.io come together in this collaborative text editing tool

I'm currently working on a collaborative app utilizing node and sockets that includes a simple text tool feature. My goal is for any user who types and applies text to the canvas to have that text visible to all other connected users. Here's wha ...

Guide on incorporating d3 axis labels within <a> elements?

Issue at Hand: I am working with a specific scale var y = d3.scalePoint().domain(['a','b','c']).range([0,100]); I have successfully created an axis for this scale var y_axis = svg.append("g").attr("class", "axis").call(d3. ...

Next.js lacks proper Tree Shaking implementation for MUI

After setting up a react app with next.js, I noticed that the bundle size for the client significantly increased when importing MUI components. Specifically, there was a large module called @mui/base added to the bundle, even though I am only using three M ...

Promise rejection caused by SyntaxError: Unexpected token i found in JSON at position 0 while trying to fetch a raw file from Gitlab

I'm attempting to retrieve a raw file from a Gitlab repository by following the official documentation. Here are the functions in question: methods: { async getProjects(url, method, payload) { const token = this.$store.getters.token ...

Is there a way to use jQuery to focus the cursor on a specific field in a form?

In my form, the first field is a dropdown with options such as "student" and "employee". Below that, there are two text fields for "college name" and "company name". If a person selects "student", then the "college name" text box should be enabled and t ...

The initial item in the Materializecss slider is failing to display

Currently, I am attempting to implement materialize slider with skrollr. The setup is functional; however, only the first item of the slider is set to opacity: 0 initially. https://i.stack.imgur.com/urSww.jpg After a brief delay, the second item becomes ...

Get JSON information based on index position

Whenever I need to generate JSON data for a shopping cart, I rely on PHP's json_encode() method: { "6cb380f1bfbcd7728be7dfbf2be6bad4": { "rowid": "6cb380f1bfbcd7728be7dfbf2be6bad4", "id": "sku_131ABC", "qty": "4", "price": "35.95", ...

Oops! Vue.js router configuration is throwing an error because it's unable to read properties of undefined when trying to access 'use'

Description: I have been working on a leaderboard web application using Vue.js. When I tried to launch the server on localhost after finishing my code, I encountered an error. The error message I received is as follows: Uncaught runtime errors: ERROR Cann ...

AngularJS - Interactive web pages powered by controller scripts

I am experiencing an issue with my AngularJS page where a popup is not displaying correctly. The popup HTML is fetched dynamically from the server using an AJAX request, including a new controller and relevant AngularJS code. The problem arises when the ch ...

Warnings about NgZone timeouts are displayed in Chrome DevTools even though the timeouts are actually executing outside of the

Is it common to receive a warning in Chrome DevTools like this? [Violation] 'setTimeout' handler took 103ms zone.js:1894 even when all timeouts are executed outside of ngzone? I personally follow this approach: this.zone.runOutsideAngular(() = ...