datatabledatatablestreetable

Select Datatable Row In Tree Table Plugin


I found a plugin which creates a hierarchal tree structure in data tables. The bonus here, is unlike most alternatives, it keeps the parent reference in the child rather than the other way around.

https://github.com/reside-ic/tree-table

As I have limited data tables knowledge, let alone data table plugin knowledge, I'm struggling to do a few of the basics (such as keying an event when selecting the row).

I have already tried the on click event which works, however this also triggers the expand and close tree triggers.

const myData = [
{
    tt_key: "a",
    tt_parent: 0,
    name: "CEO",
    salary: "10000"
},
{
    tt_key: "b",
    tt_parent: "a",
    name: "CTO",
    salary: "100"
},
{
    tt_key: "c",
    tt_parent: 0,
    name: "Developer",
    salary: "3000"
},
{
    tt_key: "d",
    tt_parent: "a",
    name: "CFO",
    salary: "10000"
}];

var table = $('#my-table').treeTable
(
    {
        select: true,
        "data": myData,
        "columns":
        [
            {
                data: "name",
                title: "Example",
            },
            {
                data: "salary",
                title: "Second Example",
            }
        ]
    }
);


table.on
(
    'click', function(e, dt, type, indexes)
    {
        alert(type);
    }
)

I need to be able to differentiate between selecting the row itself and the tree controller, column name, etc. As well as bringing through critical row information (title, salary, and so on).


Solution

  • I'm the plugin author and I've updated the plugin as per your suggestion so that row toggling now happens by default only when the icons are clicked.

    "I need to be able to differentiate between selecting the row itself and the tree controller, column name, etc. As well as bringing through critical row information (title, salary, and so on)."

    To highlight the currently selected row and log the selected row info:

        const dt = $('#my-table').DataTable();
    
        $('#my-table tbody').on('click', 'tr', function () {
    
            const $row = $(this);
            if ($row.hasClass('selected') ) {
                $row.removeClass('selected');
            }
            else {
                dt.$('tr.selected').removeClass('selected');
                $row.addClass('selected');
    
                console.log(dt.row($row).data()); // data in selected row
            }
    
        });
    

    Similarly to log info about a particular cell on a click event:

        const dt = $('#my-table').DataTable();
    
        $('#my-table tbody').on('click', 'td:not(.tt-details-control)', function () {
                console.log(dt.cell($(this)).data()); // data in selected cell
            }
        });
    

    Hope this helps!