Danae Vogiatzi Danae Vogiatzi -4 years ago 124
HTML Question

Get the text of td with specific id when checkbox is checked within the same row each time

Is there a way to get the text of a

td
from the same row as a checkbox ,when that checkbox is checked?

For example in this table:

<tr id="1">
<td id="date"> Mon, 20 Feb 2017 </td>
<td id="from" >mymail@gmail.com </td>
<td id="subject"> Hello World! </td>
<td> <input id ={{d.id}} type="checkbox" name="mycheckbox"/> </td>
</tr>
<tr id="2">
<td id="date"> Sun, 19 Feb 2017 </td>
<td id="from" >mymail@gmail.com </td>
<td id="subject"> Hello again World! </td>
<td> <input id ={{d.id}} type="checkbox" name="mycheckbox"/> </td>
</tr>


If I click the checkbox on the second row,I want to alert the subject of that row ,which is "Hello again World".

So far I have tried with
.parent()
,
.siblings()
and
closest()
,but no luck.

Answer Source

I'd used this way:

<table id="table">
<tr>
    <td> Mon, 20 Feb 2017 </td>
    <td>mymail@gmail.com </td>
    <td class="subject"> Hello World! </td>
    <td> <input type="checkbox" /> </td>
</tr>
<tr>
    <td> Sun, 19 Feb 2017 </td>
    <td>mymail@gmail.com </td>
    <td class="subject"> Hello again World! </td>
    <td> <input type="checkbox" /> </td>
</tr>  
</table>
<script>
  $('#table').on('click',':checkbox',function(){
    alert($(this).closest('tr').find('.subject').text());
  });
</script>

PS: i have removed all unused info for this case to be clear

id attribute must be unique over whole html document, never use same id for multiple elements.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download