Search code examples
javascriptjquerydatatableshtml-table

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 ?


Solution

  • 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