Asynchronous
Asynchronous

Reputation: 3977

How to get the last table cell value of the first row on a table which loads dynamically?

I have a table which is build and loaded dynamically, meaning the table is generated by code on document ready event.

I need to get the first row (not the header) and the value of the last cell when the page loads (document ready).

This is a working example:

<table id="example">
    <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Points</th>
        <th hidden="hidden">Secret Code</th>
    </tr>
    <tbody>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>
        <td>94</td>

        <!--Onload get this cell value-->
        <td hidden="hidden">1</td>
    </tr>

    <tr>
        <td>Robert</td>
        <td>Groves</td>
        <td>1000</td>
        <td hidden="hidden">2</td>
    </tr>

    <tr>
        <td>John</td>
        <td>Hamm</td>
        <td>XYZ</td>
        <td hidden="hidden">3</td>
    </tr>

    </tbody>
</table>

JS:

<script type="text/javascript">

    $(function(){

        alert($("#example tbody tr").eq(1).find('td:last').text());
    });

</script>

I cannot get this to work on the table that is being dynamically generated. I simply get an empty value.

Upvotes: 0

Views: 340

Answers (3)

Sanjay Kumar N S
Sanjay Kumar N S

Reputation: 4739

Try this:

$("#example tbody tr:first-child td:last-child" ).html();

Upvotes: 0

jaggedsoft
jaggedsoft

Reputation: 4038

In the example you provided, all is well, but we're processing hidden elements. We just have to remove them first:

$('[hidden]').remove();

Working Demo: http://jsbin.com/tebudi/edit?js,output

Upvotes: 0

<script type="text/javascript">
    $(function(){
        console.log($("#example tbody tr:first").find('td:last').html());
    });
</script>

Please use "tr:first" - it will find first row. Then find last cell "td:last". And get value from td via "html()", not "text()".

Upvotes: 1

Related Questions