user327712
user327712

Reputation: 3321

To get a value of a TD using JQuery

I got a very simple Table with only two rows.
I was thinking what is the best way to get the value from the TD with ID "row2".

<Table id="testing>
<tr>
<th>
</th>
<td id="row1">hello</td>
</tr>
<tr>
<th>
</th>
<td id="row2">world</td>
</tr>
</table>

Here is my attempt:

$(document).ready(function(){ 
      var r=$("#testing":row2).val();
      alert(r);
});

But I couldn't see any message pop up. What shall I do in the JQuery code if I want to specify the Table ID along with the TD ID?

 var r=$("#testing":row2).text();
 var r=$("#testing").children("row2").text();

Upvotes: 10

Views: 110858

Answers (4)

Sruthi Mamidala
Sruthi Mamidala

Reputation: 361

    <table>
<tr>
    <td class="tdcls">1</td>
    <td class="tdcls">2</td>
    <td class="tdcls">3</td>
</tr>
<tr>
    <td class="tdcls">4</td>
    <td class="tdcls">5</td>
    <td class="tdcls">6</td>
</tr>                   

jquery code to select particular td value

$(".tdcls").mouseenter(function(){
    var a = $(this).text();
});

Upvotes: 1

Pat
Pat

Reputation: 25675

This will do it for you:

  var r = $("#testing #row2").text();
  alert(r);

In action here for your viewing pleasure.

Upvotes: 27

Anand
Anand

Reputation: 4232

the TD ID is going to be unique be it in any table. It is not right to have two tables with TD ID's same in both tables. Therefore if you feel then append the table id for the TD ID like so: (and then use the answers above)

 <table id="test1">
    <tr>
    <th>
    </th>
    <td id="test1_row1">hello</td>
    </tr>
    <tr>
    <th>
    </th>
    <td id="test1_row2">world</td>
    </tr>
 </table>

does this help?

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382626

Use text() instead of val()

var r = $("#row2").text();

More Info:

Upvotes: 6

Related Questions