0

Edit: Click event targets static element, but function returns no value as expected.

Trying to use jQuery to get cell values of table row that user clicks. The table is dynamically generated.

Incorporated techniques from various QA on stackoverflow, but I can't get it working. What am I missing?

This QA gives very clean, clear answers, but I don't know how to apply it to a dynamically generated table: Get the contents of a table row with a button click

HTML of container:

<div id="loadQA">

     <div class="m-0 text-muted font-italic" id="outline">Nothing to see here</div>

</div>

jQuery to generate table (I doubt this is the source of the problem, but here it is anyway):

function loadQA(sectionID){
    // alert("load qa for: "+sectionID);

    $.ajax({
        type: "POST",
        dataType: "json",
        url: "data-connect.php",
        data:   {   loadQA: 1, sectionID: sectionID
        },
        success: function(data){

            var qaCount = data[0];
            var QAs     = data[1];

            // CONSTRUCT BASIC TABLE
            $("#loadQA").html(
                
                "<table class='table table-dark table-hover table-borderless' id='qaDAT'>"+
                "<thead class='darker text-orange' id='qaHead'>"+
                    "<tr>"+
                    "<th scope='col'>#</th>"+
                    "<th scope='col'>Question</th>"+
                    "<th scope='col'>Answer</th>"+
                    "</tr>"+
                "</thead>"+
                "<tbody>"+
                "</tbdoy>"+
                "</table>"

            );

            if(qaCount>0){

                for (let i = 0; i < qaCount; i++) {

                    var thisQA  = QAs[i];
                    var qaID    = thisQA[0];
                    var question= thisQA[1];
                    var answer  = thisQA[2];

                    // ADD QA DATA
                    $("#qaDAT").append(

                        "<tr id='rowDAT'>"+
                        "<th class='colDAT' scope='row'>"+qaID+"</th>"+
                        "<td class='colDAT'>"+question+"</td>"+
                        "<td class='colDAT'>"+answer+"</td>"+
                        "</tr>"

                    );

                }

            } else {

                $("#qaHead").removeClass("text-orange").addClass("text-orange-dark");
                $("#qaDAT").append(

                    "<tr>"+
                    "<td class='text-muted font-italic'>Nothing to see here</td>"+
                    "<td></td>"+
                    "<td></td>"+
                    "</tr>"

                );

            }
            
            
        }
    });

}

jQuery attempt to detect cell contents of clicked row. Click is detected, but $text returns no value:

$('#loadQA').on('click', 'tr', function () {
    var $row = $(this).closest("tr");
    var $text = $row.find(".nr").text();
    alert($text);
})
bloodymurderlive
  • 367
  • 2
  • 15

0 Answers0