How To Get Reference to Datatables Using Jquery This

How To Get Reference to Datatables Using Jquery This

anthony89anthony89 Posts: 26Questions: 8Answers: 0

I am getting the error: Uncaught TypeError: this.rows is not a function. I have a similar action for more than one datatable and am trying to create just one reference to handle interactions with them. For example:

$('.dataTable').DataTable()
    // Actions to take when row is selected/deselected
    .on( 'select', function ( e, dt, type, indexes ) {
        var selectedRowCount = this.rows('.selected').count();
        if (selectedRowCount > 0) {
            $(this).parents('.card').find('.selectedRowCount').html('( ' + selectedRowCount + ' tracks selected )');
        } else {
            $(this).parents('.card').find('.selectedRowCount').html('');
        }
    })
    .on( 'deselect', function ( e, dt, type, indexes ) {
        var selectedRowCount = this.rows('.selected').count();
        if (selectedRowCount > 0) {
            $(this).parents('.card').find('.selectedRowCount').html('( ' + selectedRowCount + ' tracks selected )');
        } else {
            $(this).parents('.card').find('.selectedRowCount').html('');
        }

This question has an accepted answers - jump to answer

Answers

  • anthony89anthony89 Posts: 26Questions: 8Answers: 0

    Ok, I think I solved it by writing the reference to it like this:

    var selectedRowCount = $(this).DataTable().rows('.selected').count();

    So, I assume that is the correct way to do it.

  • colincolin Posts: 15,237Questions: 1Answers: 2,599
    Answer ✓

    That's one way, probably the best is to use dt, the second parameter - see here,

    Colin

  • anthony89anthony89 Posts: 26Questions: 8Answers: 0

    Thanks for the reply. I made that change. Is there a better way to also make the reference when adding this code to the above:

                    // Actions to take to display a row number column
                    .on( 'order.dt search.dt', function () {
                        $(this).DataTable().column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
                            cell.innerHTML = i + 1;
                        });
                    });  
    
  • colincolin Posts: 15,237Questions: 1Answers: 2,599

    You could use a global variable, perhaps, something like:

      var table = $('#example').DataTable()
      .on('order.dt search.dt', function() {
        console.log(table.rows().count());
      });
    

    though yours would be better if there were multiple tables on the page,

    Colin

  • anthony89anthony89 Posts: 26Questions: 8Answers: 0

    I have used and do use global variable such as you made mention of, but in this case, I do have multiple tables on the page, so unless I discover a better way, I guess I will stay with $(this).DataTable().

This discussion has been closed.