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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<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="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<script>

$(document).ready(function(){    
    
    $('#add').click(function(){
                
        $('#my_tbl tr:last').after('<tr><td>&nbsp;</td><td>&nbsp;</td></tr>');        
    });
});    

</script>
</head>

<body>

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

<br />

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

</body>
</html>

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