How to Create Dynamic Add/Remove rows with input fields in HTML table using JavaScript
In this article we will create a user interface where user can add/delete multiple rows in a form using JavaScript. In my previous article, I had discussed about the dynamic PHP and html form with qty price and total in table using JavaScript calculations.
In this example, we have created a table which will display our html components. On pressing Add Button, a dynamic row will be created and added in the table and pressing Remove Button, the row will be removed.
HTML Code
<table class="table">
<tr>
<th>Action</th>
<th>Client Name</th>
<th>Phone</th>
<th>Purpose</th>
</tr>
<tr>
<td><a href="#" class="item_remove">Remove</a></td>
<td><input class="form-control" name="request[0][clientname]" type="text"></td>
<td><input class="form-control" name="request[0][phone]" type="text"></td>
<td><input class="form-control" name="request[0][purpose]" type="text"></td>
</tr>
<tr id="item_below_row">
<td colspan="100%">
<button type="button" id="add_row" class="btn btn-primary">Add</button>
</td>
</tr>
</table>
JavaScript/jQuery Code
var item_row = 1;
$("#add_row").click(function(e) {
e.preventDefault();
html ='<tr><td><a href="#" class="item_remove">Remove</a></td>\n\
<td><input class="form-control" name="request['+item_row+'][clientname]" type="text"></td>\n\
<td><input class="form-control" name="request['+item_row+'][phone]" type="text"></td>\n\
<td><input class="form-control" name="request['+item_row+'][purpose]" type="text"></td></tr>';
$("#item_below_row").before(html);
item_row++;
});
$(".table").delegate(".item_remove","click",function(e) {
e.preventDefault();
$(this).parent().parent().remove();
});
Leave a Reply