Adding new rows to table on clicking button in JQuery

Sample DEMO for Adding new row

$("#addrows").click(function () {
     $("#mytable").each(function () {
         var tds = '<tr>';
         jQuery.each($('tr:last td', this), function () {
             tds += '<td>' + $(this).html() + '</td>';
         });
         tds += '</tr>';
         if ($('tbody', this).length > 0) {
             $('tbody', this).append(tds);
         } else {
             $(this).append(tds);
         }
     });
});

Updated: Here div close at wrong place, it should end before tr close, may be thats the error

<tr id="rows">
<div style="padding-left: 5px"> 
<td style="padding:5px;" > <input type="text" name="rollno<? $i ?>"  /> </td>
<td style="padding:5px;"> <input type="text" name="firstname<? $i ?>" /> </td>
<td style="padding:5px;"> <input type="text" name="lastname<? $i ?>" /> </td>
</div> // right
</tr>
</div> // wrong

UPDATED DEMO 2


Have a look at Add table row in jQuery

which gives the solution

$('#maintable tr:last').after('<tr><td>...</td><td>...</td><td>...</td><td>...</td></tr>');

As explained here a solution with after is to be preferred over append.

Notes

  • Do not mix accessing DOM elements with jquery with the approach with getElementById.
  • As you are using jQuery there is no need to do your own AJAX function.

Demo code

http://jsfiddle.net/A5dT6/1/


try something like this,FIDDLE

    $(function () {
        $("#addRows").click(function () {
            $("#maintable").append("<tr> <td> New Row</td> </tr>")
        });
    })

Tags:

Html

Jquery