Getting Selected Rows Count Not Working After Using Iterator to Add 'selected' Class

Getting Selected Rows Count Not Working After Using Iterator to Add 'selected' Class

tdevoe@acord.orgtdevoe@acord.org Posts: 21Questions: 8Answers: 2

I originally used the following code to select all my rows in the datatable:

$('#grid').DataTable().rows({ search: 'applied' }).select();

When using this, I immediately used the following to check if the count selected > 0. The count returned is correct.
$('#grid').DataTable().rows({ selected: true }).count()

I then wanted to use the iterator for all of the rows to be able to individually select or not select the row using the following code:

$('#grid').DataTable().rows().every(function (rowIdx, tableLoop, rowLoop) {
        $(this.node()).addClass('selected')
});

After selecting rows using the iterator, I check if the count selected > 0 by using the same call used above. The count returned is 0.
$('#grid').DataTable().rows({ selected: true }).count()

I checked the source for the table rows and the 'selected' class is properly assigned to each of the table rows (tr). I compared the source from both approaches and the resulting HTML is the same.

Any thoughts as to why the behavior would be different?

Thanks.
Tom

This question has an accepted answers - jump to answer

Answers

  • gyrocodegyrocode Posts: 126Questions: 6Answers: 30

    Adding class selected is not the same as using rows().select() method even if the row appears selected.

    Use this.select() instead of $(this.node()).addClass('selected') to properly select the row.


    See more articles about jQuery DataTables on gyrocode.com.

  • tdevoe@acord.orgtdevoe@acord.org Posts: 21Questions: 8Answers: 2

    That worked perfectly. Thanks!

    I had used the following example code from this DataTables link:

    https://datatables.net/examples/api/select_single_row.html

    $('#example tbody').on( 'click', 'tr', function () {
            if ( $(this).hasClass('selected') ) {
                $(this).removeClass('selected');
            }
            else {
                table.$('tr.selected').removeClass('selected');
                $(this).addClass('selected');
            }
        } );
    

    This uses the $(this).addClass('selected') statement to select the row unless I'm not fully understanding the example.

    Thank you again for the quick response.

    Tom

  • gyrocodegyrocode Posts: 126Questions: 6Answers: 30
    Answer ✓

    The example you've mentioned doesn't use Select extension and you do in your code.

    It specifically mentions the following:

    If you are looking for a more complete and easier to use row selection option, check out the Select extension provides an API that is fully integrated with DataTables for selecting rows and acting upon those selected rows.

This discussion has been closed.