tags:

views:

200

answers:

2

i am using this to add a row dynamically to a table

   $('#myTable tr:last').after('<tr><td>1</td><td>a</td></tr>');

but it doesn't seem to work if the table has no records:

<table id="myTable" class="altTable">
    <thead>
        <tr>
            <th>
                Col1
            </th>
            <th>
                Col2
            </th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

what would be the right selector here to add a row that would work if there are 0 or > 0 rows existing ?

+1  A: 
if( !$('#myTable tbody').length )
{
  $('#myTable').append( $('<tbody>') );
}

$('#myTable tbody').append( '<tr><td>1</td><td>a</td></tr>' );
Anwar Chandra
I think this won't add rows to the inner of thead or tbody.
rahul
this will not work as per adamabtium
ooo
ok. my bad. now updated please cancel your downvote.
Anwar Chandra
done . . . . . .
ooo
+7  A: 

Try this...

$("<tr><td>1</td><td>a</td></tr>").appendTo("#myTable tbody");

That should add a row to the end of the table body tag regardless of if there are rows there already or not.

If the tbody tag won't be present w/o any rows already there then you would do this...

if ($("#myTable tbody").length > 0){
  $("<tr><td>1</td><td>a</td></tr>").appendTo("#myTable tbody");
}
else{
  $("<tbody><tr><td>1</td><td>a</td></tr></tbody>").appendTo("#myTable");
}
Ryan
This is not working for me in IE8. Basically, it results in this HTML: "<TR> 1</TD><//TD> <TD> </TD> a</TD><//TD></TR><//TR> </TR>" Idea? Thanks.
Ariel
@Ariel: I'd have to see your code.
Ryan
@Ryan: sure, I posted the issue here, http://stackoverflow.com/questions/2329319/javascript-issue-when-dynamically-adding-a-row-from-its-html-to-a-table-in-ie
Ariel