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

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

tangerinetangerine Posts: 2,142Questions: 15Answers: 236

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: 48,097Questions: 1Answers: 6,918 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: 2,142Questions: 15Answers: 236

    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: 8Questions: 1Answers: 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;
    
Sign In or Register to comment.