rshid
rshid

Reputation: 81

jquery - get td element in table

I would like to click on a anchor tag (a href) in a table and extract the contents of the next cell (or any specifc cell in that row)

$(".clCode").click(function(){
    alert( $(this).text() );
    return false;
});

<table>
<tr>
<td class='clCode'><a href="#">Select</a></td><td>Code123</td>
</tr><tr>
<td class='clCode'><a href="#">Select</a</td><td>Code543</td>
</tr><tr>
<td class='clCode'><a href="#">Select</a</td><td>Code987</td>
</tr>
</table>

Upvotes: 5

Views: 18077

Answers (5)

John Duff
John Duff

Reputation: 38598

$(".clCode").click(function(){
    alert( $(this).parent().next().text() );
    return false;
});

That should get the next td. You can also pass a selector to next() if there are more tds and you want to get something other than the first one.

$(".clCode").click(function(){
    alert( $(this).parent().next(':last').text() );
    return false;
});

Upvotes: 3

D.C.
D.C.

Reputation: 15588

you can use the jquery next() function to get a list of siblings:

$(".clCode").click(function(){
    tmp = $(this).next()[0];
    alert($(tmp).text());
});

Upvotes: 0

nil
nil

Reputation: 3641

$(".clCode a").click(function() {
    alert($(this).parent().next().html();
    return false; // optional
});

I think your HTML markup is a little bit redundant.

Upvotes: 0

Sampson
Sampson

Reputation: 268472

Getting the text from the next cell over is pretty straight forward:

$("td.clCode a").click(function(e){
  e.preventDefault();
  var nextText = $(this).parent().next().text();
});

Getting the text from another cell can be done by its index in the surrounding table-row:

$("td.clCode a").click(function(e){
  e.preventDefault();
  // Get text from fourth table-cell in row.
  var cellText = $(this).closest("tr").find("td:eq(3)").text();
});

Upvotes: 1

cletus
cletus

Reputation: 625447

$("td.clCode a").click(function() {
  var code = $(this).parent().next().text();
  alert(code);
  return false;
});

Upvotes: 0

Related Questions