Brian J Brian J - 1 month ago 6
HTML Question

How to return table row data on click of row td?

I'm trying to return the row data as an array when I click a button on that table row. Searching on SO gave me this example using

children.map
.

But when I run the web app and click a the success button on any of the table rows, the array returned in the console is empty.

enter image description here

I've verified that each table row contains data so I'm not sure why no data is returned using the map function.

I also know that the function is firing on click of the buttons with
class="btn-success".


Question:

How to return table row data on click of row td?

This is the gist of the table and the associated jQuery function to map the row data:

<table id="statusTable" class="table table-hover table-bordered results">
<thead>
<tr>
<th style="visibility:hidden;" >ID</th>
<th>IT Owner</th>
<th>ID</th>
<th>Name</th>
<th>Update Record</th>


</tr>
</thead>
<tbody>
@foreach (var row in Model.ReleaseStatus)
{
<tr>
<td style="visibility:hidden;" >@Html.Raw(row.ID)</td>
<td>@Html.Raw(row.Configuration)</td>
<td id="app_name" class="links" style="font-size: 14px;">@row.ID</td>
<td>@row.Configuration_Item</td>
<td>@row.Configuration_Name</td>
<td><button type="submit" class="btn btn-success btn-lg">Update</button></td>
</tr>
}
</tbody>

</table>


JQuery function:

$(".btn-success").click(function () {
var tableData = $(this).children("td").map(function () {
return $(this).text();
}).get();

console.log(tableData);
});

Answer

You need to find tr, then tds

Updated

__HTML

<table>
    <tr>
        <td>col #1</td>     
        <td>col #2</td>
        <td>            
            <button type="button">click me</button>
        </td>
    </tr>
</table>

JS

$("button").click(function() {
    var $td = $(this).closest('tr').children("td"),
        len = $td.length;       

    var tableData = $td.map(function(i) {   
        if(i < len -1)
            return $(this).text();
    }).get();

    console.log(tableData); // ["col #1", "col #2"]
});

jsfiddle

Comments