Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery- Get the value of first td in table

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 closest('tr').. but it always output "Object object". Not sure what to do on this one.

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)  ;

});
like image 736
FlyingCat Avatar asked May 28 '10 17:05

FlyingCat


People also ask

How to get first td value in Javascript?

I would start by having your listener for the click a bit more specific so its not triggering on any click on the entire table. Then you were very close by getting the tr , from there you can pass the tr into the del function and use getElementsByTagName on the tr to return the first td from the tr .

How can get current TR data in jquery?

$(this). closest('tr'). children('td:eq(0)'). text();


3 Answers

$(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.

like image 72
Tesserex Avatar answered Oct 19 '22 04:10

Tesserex


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.

like image 46
Felix Kling Avatar answered Oct 19 '22 02:10

Felix Kling


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

$(this).parents("tr").children("td:first").text()
like image 13
Inaimathi Avatar answered Oct 19 '22 02:10

Inaimathi