Retrieving parent row data from its child row - best practice?

Retrieving parent row data from its child row - best practice?

tangerinetangerine Posts: 3,365Questions: 39Answers: 395

This is retrieving the id correctly, but 1) Using DOM elements seems a bit cumbersome, and 2) I would prefer to access the required data item by name. Any suggestions welcome.

$("#datatable tbody").on("click", "span#more", function () {
    // Get parent row (object HTMLTableRowElement)
    var parentRow = $(this).closest("tr").prev()[0];

    var cells = parentRow.cells ;
    var id = cells[0].innerText;
....

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,679Questions: 1Answers: 10,498 Site admin
    Answer ✓

    How about:

    $("#datatable tbody").on("click", "span#more", function () {
        // Get parent row (object HTMLTableRowElement)
        var parentRow = $(this).closest("tr").prev()[0];
     
        var rowData = table.row( parentRow ).data();
        var id = rowData.id; // or whatever it is
    ....
    

    You need to use DOM / jQuery methods to traverse from the child row to the host. That's something I want to add into the row selectors in future.

    Allan

  • tangerinetangerine Posts: 3,365Questions: 39Answers: 395

    Thanks, Allan. That does it.
    I had been looking at something similar in the first place, but kept getting "undefined" for the id. Turns out I had forgotten that I needed a tablename.fieldname reference -

    var id = rowData.tablename.fieldname;
    

    It's tripped me up more than once now. Looks like I'm destined never to learn...

  • stolstol Posts: 16Questions: 2Answers: 1

    This worked best for me:

    var tr = $(this).closest('tr').parents('tr'); 
    var prevtr = tr.prev('tr')[0];
    var data = table.row(prevtr).data();
    var orderid = data.fieldname;
    
This discussion has been closed.