0

I have a HTML table as below :

 <table> <tr> <th>Name</th> <th>Class</th> <th>Reg ID</th> </tr> <tr> <td>Alex</td> <td>VII</td> <td>56733</td> </tr> <div id="addfield"></div> </table> <input type="button" value="add" id="add_more_fields" /> 

And the jquery :

$(document).ready(function(){ var html = ''; $('#add_more_fields').click(function(){ html += '<tr>'; html += '<td>Steve</td>'; html += '<td>X</td>'; html += '<td>87777</td>'; html += '</tr>'; $('#addfield').append(html); }); }); 

I wanted to add the <tr> generated by the javascript to be within the table. but when I clicked the button, the output is shown outside the table ! How can I display it within the table ?

DEMO Here

1
  • 2
    i think you need to give the id to Table instead of Div [Updated Fiddle] (jsfiddle.net/2yBYb/1) Commented Jan 9, 2014 at 6:02

4 Answers 4

1

It is not working because div inside table is invalid HTML structure. Append row to the table itself.

Also, you are not clearing the string html. Which causes multiple rows.

$('#add_more_fields').click(function () { var html = ''; //declare string inside function html += '<tr>'; html += '<td>Steve</td>'; html += '<td>X</td>'; html += '<td>87777</td>'; html += '</tr>'; $('table').append(html); }); 

Updated fiddle here.

Sign up to request clarification or add additional context in comments.

2 Comments

One more query...what if I am having more than one table ?
@Nitish give id/class to table and access it.
1

Try tbody inplace of #addfield like,

<table> <thead> <tr> <th>Name</th> <th>Class</th> <th>Reg ID</th> </tr> </thead> <tbody> <tr> <td>Alex</td> <td>VII</td> <td>56733</td> </tr> </tbody> </table> 

SCRIPT

$('#add_more_fields').click(function(){ html += '<tr>'; html += '<td>Steve</td>'; html += '<td>X</td>'; html += '<td>87777</td>'; html += '</tr>'; $('tbody').append(html); }); 

Demo

Comments

1

Append Inside table

$('#add_more_fields').on('click',function(){ html += '<tr>'; html += '<td>Steve</td>'; html += '<td>X</td>'; html += '<td>87777</td>'; html += '</tr>'; $('table').append(html);//If you have more table then use id for table to append }); 

Comments

0

You can't have a div inside a table. All you've gotta do is put the id on the table and remove the div.

<table id='addfield'> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.