Dev1ce
Dev1ce

Reputation: 5944

Datatable column onClick

I am referring the following Datatable example -

https://datatables.net/examples/api/select_single_row.html
The example captures onclick event on the entire row

$('#example tbody').on( 'click', 'tr', function (){}

I wish to capture an event on the click of a particular columns, say column Name, Position and Office. How do I do that?

Upvotes: 2

Views: 21525

Answers (2)

Carlos Cuesta
Carlos Cuesta

Reputation: 1484

You can access clicks in columns hooking and event handler in the elements you want in the fnRowCallback. Here is a complete example with a table with 2 extra columns showing an icon that receives the click:

$('#example').DataTable({
        dom: 'lfrt',
        paging: false,
        rowBorder: true,
        hover: true,
        serverSide: false,
        rowHeight: 30,
        order: [[ 1, 'asc' ]],
        columns: [
            {
                title: 'Id',
                visible: false,
                searchable: false
            },
            {
                title: 'version',
                visible: false,
                searchable: false
            }                {
                title: Name'
            },
            {
                data: null,
                title: 'Diagram',
                searchable: false,
                sortable: false,
                defaultContent: '<i class="fa fa fa-sitemap icon-btn" data-btnaction="grafo"></i>',
                className: 'text-center'
            },
            {
                data: null,
                title: 'History',
                searchable: false,
                sortable: false,
                defaultContent: '<i class="fa fa-history icon-btn" data-btnaction="appdetail"></i>',
                className: 'text-center'
            }

        ],
        select: false,
        fnRowCallback: function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
            $('td > i', nRow).on('click', function() {
                // if you have the property "data" in your columns, access via aData.property_name
                // if not, access data array from parameter aData, aData[0] = data for field 0, and so on...
                var btnAction = $(this).data('btnaction');
                if (btnAction === 'grafo'){
                } else if (btnAction === 'appdetail'){
                    // do something......
                }
            });
        }
    });

Upvotes: 0

WhoAmI
WhoAmI

Reputation: 501

If you know the table colums index then you might you use this.

$('#example tbody').on( 'click', 'tr td:eq(0)', function (){
   alert("col1");
});
$('#example tbody').on( 'click', 'tr td:eq(1)', function (){
   alert("col2");
});
$('#example tbody').on( 'click', 'tr td:eq(4)', function (){
   alert("col5");
});

Upvotes: 3

Related Questions