Today, I will share a simple way to implement cloning and removing tr dynamically and how to keep the last tr without removing it.
*Requirements Below: *
- A Selector to append TR
- add/remove selector class
<table class="table table-hover">
<thead>
<tr>
<th>Product </th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody class="productServicesTbody">
<tr>
<td>
<input
type="text"
class="form-control"
/>
</td>
<td>
<input
type="text"
class="form-control"
/>
</td>
<td>
<button type="button" class="btn btn-primary btn-sm addTr">
Add
</button>
<button type="button" class="btn btn-danger btn-sm removeTr">
Delete
</button>
</td>
</tr>
</tbody>
</table>
JS Code
$(document).ready(function() {
$(document).on('click', '.addTr', function() {
let $clone = $(this).closest('tr').clone();
$clone.find('input').val('');
$('.productServicesTbody').append($clone);
});
$(document).on('click', '.removeTr', function() {
if ($('.productServicesTbody tr').length > 1) {
$(this).closest('tr').remove();
}
});
});
Here .addTr is an add new tr button selector. And .removeTr is an add new tr button selector.
Please, let me know your queries in the comment section.
Top comments (0)