views:

157

answers:

5

Hello. I am trying to get the value of first td in each tr when a users clicks "click".

The result below will output aa ,ee or ii. I was thinking about using clesest('tr')..but it always output "Object object". Not sure what to do on this one. Thanks.

My html is

<table>
<tr>
  <td>aa</td>
  <td>bb</td>
  <td>cc</td>
  <td>dd</td>
  <td><a href="#" class="hit">click</a></td>

</tr>
<tr>
  <td>ee</td>
  <td>ff</td>
  <td>gg</td>
  <td>hh</td>
  <td><a href="#" class="hit">click</a></td>
</tr>
<tr>
  <td>ii</td>
  <td>jj</td>
  <td>kk</td>
  <td>ll</td>
  <td><a href="#" class="hit">click</a></td>
</tr>

</table>

Jquery

$(".hit").click(function(){

 var value=$(this).// not sure what to do here

 alert(value)  ;

});
+3  A: 
$(this).parent().siblings(":first").text()

parent gives you the <td> around the link,

siblings gives all the <td> tags in that <tr>,

:first gives the first matched element in the set.

text() gives the contents of the tag.

Tesserex
+3  A: 

This should work:

$(".hit").click(function(){    
   var value=$(this).closest('tr').children('td:first').text();
   alert(value);    
});

Explanation:

  • .closest('tr') gets the nearest ancestor that is a <tr> element (so in this case the row where the <a> element is in).
  • .children('td:first') gets all the children of this element, but with the :first selector we reduce it to the first <td> element.
  • .text() gets the text inside the element

As you can see from the other answers, there is more than only one way to do this.

Felix Kling
Thanks. your code works.!
Jerry
You all give correct answers! Since you already have 16K and Tesserex replied me first. I will give the accepted answer to Tesserex. Thanks a lot! +1 to u all.
Jerry
+1  A: 

Install firebug and use console.log instead of alert. Then you will see the exact element your accessing.

Marc
good tip! thanks.
Jerry
+2  A: 
$(".hit").click(function(){
   var values = [];
   var table = $(this).closest("table");
   table.find("tr").each(function() {
      values.push($(this).find("td:first").html());
   });

   alert(values);    
});

You should avoid $(".hit") it's really inefficient. Try using event delegation instead.

Caleb
cool! your way is a bit complex to me, but +1. Thanks.
Jerry
I think the OP wants to get the value of the first cell in the current row, not all rows.
Felix Kling
+1  A: 

In the specific case above, you could do parent/child juggling.

$(this).parents("tr").children("td:first").text()
Inaimathi
`closest` only looks for ancestors of the current element. Your second example would not work. And your first example does not work either because `parent()` only traverses on level up in the DOM hierarchy (you maybe mean `parents()`).
Felix Kling
Edited for correctness.
Inaimathi