In this post we will see how to add and remove rows from table in jQuery. For adding and removing rows we will use various attributes and functions in jQuery.
There are many ways for adding or removing rows in table using jQuery. I found this way to be the easiest way.
Add and Remove rows from table in jQuery
1. Include the JS file for jquery
1 |
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script> |
2. Add the table structure in HTML. (I have also added some test data). For each row we provide a delete button and a single Add new row button
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<body> <button onClick="addNewRow()">Add New Row</button> <hr/> <table id="empData"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Department</th> <th>Salary</th> <th></th> </tr> </thead> <tbody> <tr> <td>John</td> <td>Smith</td> <td>Sales</td> <td>$7,500</td> <td><img src='images/delete.png' onClick='deleteRow(this)'/></td> </tr> <tr> <td>Steve</td> <td>Doe</td> <td>Sales</td> <td>$8,500</td> <td><img src='images/delete.png' onClick='deleteRow(this)'/></td> </tr> </tbody> </table> </body> |
3. Add the Javascript methods
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$(document).ready(function(){ addNewRow = function(){ $("#empData tbody").append( "<tr>" + "<td>New Row</td>" + "<td>New Row</td>" + "<td>New Row</td>" + "<td>New Row</td>" + "<td><img src='images/delete.png' onClick='deleteRow(this)'/></td>"+ "</tr>"); } deleteRow = function(element){ $(element).parent().parent().remove(); } }); |
Output
When you run the html file in browser