How to get a value of the closest td with class on button click?
Asked Answered
J

3

17

I have table rows with data and buttons. http://codepen.io/leongaban/pen/nuIkd

Each button corresponds to each row, also when you click a button it changes class names from hide to un_hide the next step is to retrieve the text value of the td with class contact_name in the row that the clicked button belongs too.

Table structure:

<tr>
  <td class="contact_name" style="padding: 7px 0;">
    Name 1
  </td>
  <td>
      <button class="btn_hide">Hide</button>
  </td>
</tr>
<tr>
  <td class="contact_name" style="padding: 7px 0;">
      Name 2
  </td>
  <td>
      <button class="btn_hide">Hide</button>
  </td>
</tr>

Using this jQuery, it will get ALL text values of .contact_name in all the rows

var name = $('.contact_name').text();

So I tried this to get the text value of the 'closest' .contact_name td

var name = $(this).closest('.contact_name').text();

However that returns blank for me :(

How would you get the Name 1 value by clicking the first Hide button?

Juliettejulina answered 17/12, 2013 at 17:44 Comment(1)
$(this).closest('td').siblings('.contact_name').text()Yeryerevan
D
50

.contact_name is not parent from the clicked button.

var name = $(this).closest('tr').find('.contact_name').text();
Dublin answered 17/12, 2013 at 17:45 Comment(0)
A
5

Try,

var name = $(this).closest('td').prev('.contact_name').text();

Or

var name = $(this).closest('tr').find('.contact_name').text();

DEMO

Agio answered 17/12, 2013 at 17:47 Comment(0)
D
2
var name = $(this).closest('tr').children('.contact_name').text();
Disparage answered 17/12, 2013 at 17:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.