Question

I have a basic HTML table with a button in each row. By click on the button I want to alert the text from the second TD in the same TR.

For some reason the below does not work and either returns nothing or null (depending on whether I try .text() or .html() ). parent instead of closest failed as well. Can someone tell me what I am doing wrong here ? (My table has the ID "myTable" and all TRs are in a TBODY, if needed.)

Example TR:

<tr><td style="width:30%"><strong>Row 1:</strong></td><td id="fldRow1" style="width:60%">test text</td><td><button type="button" id="copyRow1" onclick="copyOutput()">Copy</button></td></tr>

JS function:

function copyOutput() {
    var output = $(this).closest('tr').find('td:eq(1)').text();
    alert(output);
}

Many thanks for any help with this, Tim.

Was it helpful?

Solution

thisin you code not refer to the current element it refers to the window object.

HTML

Change

onclick="copyOutput()"

to

onclick="copyOutput(this)" //pass refer of the current element


js

function copyOutput(el) { //el get current element clicked
    var output = $(el).closest('tr').find('td:eq(1)').text();
    alert(output);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top