Thursday, August 26, 2010

How to add table row (tr) using jQuery

I think the easiest method is to find the last tr and insert the new row after the last tr.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>How to add table rows using jQuery</title>

<script type="text/javascript" src=""></script>


        $('#my_tbl tr:last').after('<tr><td>&nbsp;</td><td>&nbsp;</td></tr>');        



<table id="my_tbl" border="1" cellpadding="1" cellspacing="1">
        <td> Head1 </td>
        <td> Head2 </td>

<br />

<input type="button" id="add" value="Add Row" />


View Demo

The only place where this code does not work is when there are no tr's in the table to start with. If that is the case you can always add a dummy <tr></tr> block to the top to start with.

Please comment if you know a better solution.

No comments:

Post a Comment