tags:

views:

178

answers:

5

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>
A: 
$("td.clCode a").click(function() {
  var code = $(this).parent().next().text();
  alert(code);
  return false;
});
cletus
+1  A: 

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();
});
Jonathan Sampson
Why not `$(this).closest('td').next().text()` directly?
K Prime
@K, The link (according to the example) is immediately within the TD. Calling the `closest("td")` would make more sense if the link were a grandchild of the TD, and not an immediate child.
Jonathan Sampson
A: 
$(".clCode a").click(function() {
    alert($(this).parent().next().html();
    return false; // optional
});

I think your HTML markup is a little bit redundant.

nil
A: 

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

$(".clCode").click(function(){
    tmp = $(this).next()[0];
    alert($(tmp).text());
});
darren
+1  A: 
$(".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;
});
John Duff