Here is a simple append function
using jQuery, and it's working perfectly.
However, the issue arises when I try to append a button
and remove the parent tr
upon clicking. The problem lies in using remove parent
, as it doesn't seem to work as expected.
The function works fine if the button
already exists on the page. However, when I dynamically add a new one using the add button function, the removal process does not function correctly.
$(document).ready(function() {
$(".add-row").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var markup = `
<tr>
<td>` + name + `</td>
<td>` + email + `</td>
<td><button type="button" class="delete-row">Delete Row</button></td>
</tr>
`;
//VALIDATION
if (name && email) {
$("table tbody").append(markup);
$('.req').remove();
} else {
$('.req').remove();
}
//REQUIRED
if (!name) {
$('#name').after(`
<div class="req">
<small class="text-secondary text-danger" style="font-size: 10px;">
<i>* Name must not be empty</i>
</small>
</div>
`);
}
if (!email) {
$('#email').after(`
<div class="req">
<small class="text-secondary text-danger" style="font-size: 10px;">
<i>* Email address must not be empty</i>
</small>
</div>
`);
}
});
$(".delete-row").click(function() {
$(this).parents("tr").remove();
});
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a7c5c8c8d3d4d3d5c6d7e79389918997">[email protected]</a>/dist/css/bootstrap.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<div class="container mt-2">
<form>
<div class="row">
<div class="col-4">
<input type="text" id="name" placeholder="Name" class="form-control" required>
</div>
<div class="col-4">
<input type="text" id="email" placeholder="Email Address" class="form-control" required>
</div>
<div class="col-4">
<button type="button" class="add-row btn btn-success"> ADD </button>
</div>
</div>
</form>
<br>
<br>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Select</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>One 1</td>
<td>One 1</td>
<td><button type="button" class="delete-row">Delete Row</button></td>
</tr>
<tr>
<td>Two 2</td>
<td>Two 2</td>
<td><button type="button" class="delete-row">Delete Row</button></td>
</tr>
<tr>
</tbody>
</table>
</div>