prakashchhetri
prakashchhetri

Reputation: 1816

Get the unique data of td with Jquery

I need to get the data of the selected td items. In this case say I want the data of second <td> item from each row. I tried a simple Jquery to get the HTML, but it would get the same data (i.e the data from the first <tr> -> second <td>. How do i get the data from second row and the consecutive row.

EDIT

I want to get the data (the text of td) when the respective link is clicked.

<table>
<tr>
  <td>1</td>
  <td class="name">First</td>
  <td>something else</td>
  <td><a class="link">Order</a></td>

</tr>
<tr>
  <td>2</td>
  <td class="name">second</td>
  <td>something else</td>
  <a class="link">Order</a>

</tr>
</table>

The functions I used would simply get the data from first td with that class only. I think I need to use something like parent(). But I have very little knowledge of Jquery.

var itemName = $('td.itemname').html();

or

var itemName = $('.itemname').html();

Upvotes: 0

Views: 1106

Answers (3)

devrooms
devrooms

Reputation: 3149

Assuming that you want this to work when you click a link, then:

$(function(){
  $("a.link").click(function() {
    var secondTd = $(this).parents("tr").find("td.name").first();
    alert(secondTd.html());
  });
});

Upvotes: 2

Hanlet Esca&#241;o
Hanlet Esca&#241;o

Reputation: 17380

Use the nth function like this:

$('table tr td:nth-child(2)').text();

This will give you the text of all of the second columns. the nth function is not zero-based.

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191749

var tdValues = [];
$(".name").each(function () {
    tdValues.push($(this).text());
});

Now you have an array of the text content of each td in the variable tdValues.

If you only want the second row:

var tdValue = $("tr:eq(1) .name").text();

If you want the second row and on,

$("tr:gt(0) .name").each(...)

EDIT:

$(".link").on('click', function () {
    var text = $(this).closest('tr').find('.name').text();
});

Upvotes: 3

Related Questions