Dynamically Add and Remove rows in a Table Using jQuery
The following example shows, how to dynamically add and remove rows in a table using jQuery.In this example, we have created a HTML table which will display one row that contains input fields. On clicking +Add Row
row button, a row will be appended in the table. To remove a row, we have to click the Remove
button in the same row.
Example
<html> <head> <title>Dynamically Add/Remove Table Rows using jQuery</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <style> #tbl{ width:50%; margin:50px auto; border-collapse:collapse; } #tbl td,#tbl th{ border:1px solid #ccc; padding:15px; } </style> </head> <body> <table id='tbl'> <thead> <tr> <th>Name</th> <th>Age</th> <th>Remove</th> </tr> </thead> <tbody> <tr> <td><input type='text' name='uname[]'></td> <td><input type='text' name='age[]'></td> <td><input type='button' value='Remove' class='rmv'></td> </tr> </tbody> <tfoot> <tr> <td colspan='3'><input type='button' value='+Add Row' id='add_row'></td> </tr> </tfoot> </table> <script> $(document).ready(function(){ $("#add_row").click(function(){ var row="<tr> <td><input type='text' name='uname[]'></td> <td><input type='text' name='age[]'></td> <td><input type='button' value='Remove' class='rmv'></td> </tr>"; $("#tbl tbody").append(row); }); $("body").on("click",".rmv",function(){ $(this).closest("tr").remove(); }); }); </script> </body> </html>Try it Yourself