JQuery - getting the text value of a table cell in the same row as a clicked item

I click the link in the table cell. I need to get the value of a specific cell inside the same row of the table.

<tr> <td class="one">this</td> <td class="two">that</td> <td class="three">here</td> <td class="four"><a href="#">there</a></td> </tr> <tr> <td class="one">qwqw</td> <td class="two">dfgh</td> <td class="three">ui</td> <td class="four"><a href="#">there</a></td> </tr> 

I have a click handler attached to a link in the fourth cell. This click handler calls a function that opens a modal window. When a form is submitted in modal format, I also want to pass the value of td class = "two" from the line to which the link to this modal was clicked.

Here is the function that sends the modal (the problem area gets the correct value for var Something):

 var Send = function() { var Name = $( '#name' ).val(); var Something = $(this).closest('td').siblings('.two').text(); // version 1. doesn't work var Something = $(this).closest('tr').siblings('td.two').text(); // version 2 also doesn't work var Something = $(this).attr('class'); // version 3. just a test but also doesn't work $.ajax( { async: false, data: { name: Name, somedata: Something }, type: 'POST', url: the url }); }; 

The problem is that I cannot get the correct value for Something. This should be the value of td class = two on the same line as the click.

How it all happens together. Click the destination link that calls the Send_Click () method. Send_Click does some checks and then calls Send (), but the value for Something is never populated. Is it because this not what I think so? Hjelp!

+42
jquery jquery-selectors
Feb 23 '10 at 1:40
source share
5 answers

You want instead of .children() ( here ):

 $(this).closest('tr').children('td.two').text(); 
+64
Feb 23 2018-10-23T00
source share

Nick has the correct answer, but I wanted to add that you can also get cell data without having to use the class name

 var Something = $(this).closest('tr').find('td:eq(1)').text(); 

:eq(#) has an index based on zero ( link ).

+57
Feb 23 '10 at 2:52
source share

it should work fine:

 var Something = $(this).children("td:nth-child(n)").text(); 
+5
Jun 16 '11 at 16:15
source share

so that you can use parent () to access the parent tr, and then use find to collect td with the second class

  var Something = $ (this) .parent (). find (". two"). html (); 

or

  var Something = $ (this) .parent (). parent (). find (". two"). html (); 

use as much as parent () so that the depth of the clicked object according to tr row

hope it works ...

+4
Feb 23 2018-10-02T00
source share

It will also work

 $(this).parent().parent().find('td').text() 
+4
Jul 10 2018-12-12T00:
source share



All Articles