0

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.

3
  • $table.on('click', 'td'..., because 'td:eq(1)' means only for the first td Commented Aug 16, 2018 at 11:38
  • No. td:eq(1) means column index 1, not the row 1. Commented Aug 16, 2018 at 11:49
  • eq does not mean column index 1. it means the position of an element within a set. in this case, you don't know if the set is the the set of all TDs in a row, all TDs in the table, or even just the specific TD being clicked. try $table.on('click', 'td:nth-child(1)' Commented Aug 16, 2018 at 11:55

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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!

Comments