tags:

views:

49

answers:

3

Hi all,

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();
+3  A: 

This will do it for you:

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

In action here for your viewing pleasure.

Pat
Thanks Pat. Could you show me the Jquery code if I want to specify which Table the TD belongs to instead of just the TD ID.
Absolument - I've edited the code above to add the table's ID to the selector. However, strictly speaking, this shouldn't be required in your case because an ID should be unique in the document (i.e. you shouldn't have any `row2` IDs anywhere else). If you need multiple row2's, you could use classes: `<td class="row2">`, in which case your selector would become `$("#testing .row2")`. You can read more about selectors here: http://api.jquery.com/category/selectors/. The short version is that if the selector works in CSS, it'll work in jQuery.
Pat
Thank you again for the help, Pat.
+2  A: 

Use text() instead of val()

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

More Info:

Sarfraz
A: 

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?

Anand