Tyson
Tyson

Reputation: 149

JQuery Append Data at end of table

<table id="myTable0" name="myTable0">
<tbody>
<tr>
</tr>
</tbody>
</table>

<table id="myTable1" name="myTable1">
<tbody>
<tr>
</tr>
</tbody>
</table>

I need some JQuery that will attempt to append new html to the end of a table and do it on the enter key, it will also select the correct table to append it to as there are numerous tables.

Here is my code that doesn't work but attempts to do this:

for (i=0; i<2; i++)
  {
$("#newComment" + i).keyup(function(event){
    if(event.keyCode == 13){
        var $test= $('<tr><td>content here</td></tr>');
        $('#myTable '+ i + ' > tbody:last').append($test);
    }
}

The line that is throwing me problems is the Jquery select which follows:

$('#myTable '+ i + ' > tbody:last').append($newdiv1);

Upvotes: 1

Views: 7715

Answers (3)

Przemek Lewandowski
Przemek Lewandowski

Reputation: 516

Is there a typo? I think you mean $test instead if $newdiv1 in a problematic line.

I can see you have only one <tbody> tag so the ':last' selector is not necessary. I think that

$('#myTable' + i + ' tbody').append($test);

will be fine.

Edit: Yup, as Rajat Singhal said remove sapce in selector after #myTable.

Upvotes: 1

Vinee
Vinee

Reputation: 1654

Yup this is very simple just do like this

$('#myTable'+ i).find('tr:last').append($test);

And thats done.

Upvotes: 2

Rajat Singhal
Rajat Singhal

Reputation: 11264

Try this:

$('#myTable' + i + ' > tbody:last').append($newdiv1);

The space $('#myTable ' is the problem..

You are having space between #myTable and 0..

You need #myTable0 while you were having #myTable 0

Upvotes: 6

Related Questions