user866364
user866364

Reputation:

Datatables - How to implement click on columns of every rows?

I'm trying to implement a click function on a specific column but it's only working for the first row.

My table is dynamic and the content is based on stream from web sockets.

Here is what I'm trying to do:

function initTable($table) {
  window.dataTable = dataTable = $table.DataTable({
      data: workerObjects,
      columns: [
          { title: "Agent", data: "friendlyName" },              
          { title: "Listen",
            render: function(data, type, row) {                
              if ( !row.task ) { return '-' }                  
              return `<a href='#' id="join_${row.task.sid}"><i id="${row.task.sid}" class="fa fa-play-circle"></i></a>`
            }
          },
      ],
      pageLength: 25
  });

  // https://github.com/benjamine/jLiveTime
  $table.livetime();

  $table.on('click', 'td:eq(1)', function (event) {
    console.log('bang';
  });

  return dataTable;
}

In a specific flow, I run dataTable.rows().invalidate().draw(); to update table because object workerObjects has been updated.

How can i make $table.on('click', 'td:eq(1)'... works for every row? Right now, it's only working for first row.

Upvotes: 0

Views: 1041

Answers (2)

Sivaprasath
Sivaprasath

Reputation: 400

You can do the same using the below code,

$table.find('tbody').on('click', 'tr', function () {
    var data = dataTable.row(this).data();
    alert( 'You clicked on '+data[0]+'\'s row' );
} );

As mentioned in the original documentation itself. Please go through the link below for your reference,

https://datatables.net/examples/advanced_init/events_live.html

Hope it helps!

Upvotes: 0

Kae Verens
Kae Verens

Reputation: 4079

use

$table.on('click', 'td:nth-child(1)', function (event) {

my understanding of your code is that it currently will trigger on literally the first TD in the table (eq being a collection of all TDs in the table)

Upvotes: 1

Related Questions