tbody selector confusion

tbody selector confusion

hzhonghzhong Posts: 11Questions: 3Answers: 0
edited July 7 in DataTables

When trying to get the data for the selected row, below code from the documentation https://datatables.net/reference/api/row().data() doesn't work for me:

var table = $('#example').DataTable();
 
$('#example tbody').on( 'click', 'tr', function () {
    console.log( table.row( this ).data() );
} );

However it works after I removed the tbody selector and just used the id of example as selector:

var table = $('#example').DataTable();
 
$('#example').on( 'click', 'tr', function () {
    console.log( table.row( this ).data() );
} );

Everything else works well. Did I set anything wrong for the datatable?
Thank you.

This question has accepted answers - jump to:

Answers

  • kthorngrenkthorngren Posts: 14,210Questions: 25Answers: 3,357
    edited July 7 Answer ✓

    Probably depends on whether the tbody is in the DOM or not when the `$('#example tbody').on( 'click', 'tr', function () { .. }); statement is executed. If it is not in the DOM then the delegated event won't be created. See the jQuery delegated events doc for more info.

    Your first code snippet works in this example:
    http://live.datatables.net/womajoqi/1/edit

    If you still have questions please provide a test case showing the problem so we can provide more specific help.

    Kevin

  • kthorngrenkthorngren Posts: 14,210Questions: 25Answers: 3,357
    Answer ✓

    Just thought of something. If you are using Ajax loaded data then the first code snippet might execute before Datatables initialization has taken place - meaning the tbody might not be in the DOM yet. You can add the code into initComplete if you want the tbody as part of the selector.

    Kevin

  • hzhonghzhong Posts: 11Questions: 3Answers: 0

    Thank you Kevin.

    With Ajax loaded data, can I just put the first code snippet after the statement of datatable initialization?

    I realized in my initial test, I put the code before the datatable initialization, which certainly won't work as the tbody is not in DOM yet. But it works after I put it after the datatable statement. I assume the tbody is available in DOM after the table completes its initial run and before the data has been loaded. Is it correct?

  • kthorngrenkthorngren Posts: 14,210Questions: 25Answers: 3,357
    Answer ✓

    If it works then it should be ok. The safest place is to place the event handler code in initComplete then you know the DOM table is in place.

    Kevin

  • hzhonghzhong Posts: 11Questions: 3Answers: 0

    Thank you Kevin.

Sign In or Register to comment.