Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Rowspan in JQuery datatables

Im using Jquery datatables to construct a table.
My requirement is like below
enter image description here

This is not a static table, and we are rendering it using json data.
Here I'm, rendering the rows dynamically using "aoColumns".
Is there any way to use rowspan so that the cells (1,2,David,Alex) can be spanned.
Does datatables support this kind of table ?

like image 453
Shree Avatar asked Aug 19 '15 07:08

Shree


2 Answers

Datatables does not support this kind of grouping out of the box. But, as in many cases, there is a plugin available.

It is called RowsGroup and is located here: Datatables Forums. A live example is also included.

If you change the JS part in this example to the below you will have your desired output presented to you in the output window.

$(document).ready( function () {
  var data = [
    ['1', 'David', 'Maths', '80'],
    ['1', 'David', 'Physics', '90'],
    ['1', 'David', 'Computers', '70'],
    ['2', 'Alex', 'Maths', '80'],
    ['2', 'Alex', 'Physics', '70'],
    ['2', 'Alex', 'Computers', '90'],
  ];
  var table = $('#example').DataTable({
    columns: [
        {
            name: 'first',
            title: 'ID',
        },
        {
            name: 'second',
            title: 'Name',
        },
        {
            title: 'Subject',
        }, 
        {
            title: 'Marks',
        },
    ],
    data: data,
    rowsGroup: [
      'first:name',
      'second:name'
    ],
    pageLength: '20',
    });
} );

Here is a screenshot of the result:

enter image description here

like image 80
DKSan Avatar answered Nov 01 '22 06:11

DKSan


I tried the RowsGroup plugin, but it achieves this just by hijacking the DataTables sort mechanism. If you tell it to group a given column, what it does for you is basically to apply a sort to that column that you can't turn off. So, if you want to sort by another column, you can't. That didn't work in my application.

Instead, here's a working fiddle for a recipe that allows you to achieve this result:

https://jsfiddle.net/bwDialogs/fscaos2n

The basic idea is to flatten all of your multi-row data into a single row. Content in your 2nd, 3rd, etc. rows are stored as a hidden <script> template tag within your first row.

It works by using DataTables' drawCallback function to manipulate the DOM once DataTables has rendered it, without confusing DataTables by having to try parsing rowspan cell content.

Since this modifies the DOM after DataTables has done its magic, your multi-row sections will stick together even with pagination, searching, and sorting.

Cheers.

like image 25
BrentW Avatar answered Nov 01 '22 06:11

BrentW