I use thymeleaf with js.
<form class="row" id="testamentExecutor">
<div id="executorsSection" class="form-row">
<div th:insert="fragments/executor :: executor" th:remove="tag" />
</div>
<div id="executorSectionAdd" class="deleteButton">
<a href="#" class="link-primary" id="addExecutor">Add</a>
</div>
</form>
Code of framents/executors
Click event on addExecutor allow to add another bloc of executorSection. AlternativeExecutor section is include in executorSection but it's hided.
<script type="text/javascript" th:inline="javascript">
$(document).ready(function() {
$(".delete-executor").on('click', function (e) {
e.preventDefault();
$(this).parent().parent().remove();
});
$("#addExecutor").on('click', function (e) {
e.preventDefault();
$.ajax({
url: "/executor",
success: function (data) {
$("#executorsSection").append(data);
$("#executorSection, #executorSectionAdd, .deleteButton").removeClass('visually-hidden');
let nbExecutor = $('.executorSection').length;
if (nbExecutor == 2) {
$("#executorSectionAdd").addClass('visually-hidden');
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
});
});
</script>
When I add another executor, it's event (delete-executor, addAlternativeExecutor, delete-alternative-executor) is not working for them
If you're adding new elements to the DOM after the definition of your event listeners, the event listeners will not work on the newly added elements.
You can add event listeners only to elements that already exist in the DOM at the moment when listeners are defined.
Each time you add a new element to the DOM you have to attach a new event listener to it (if you need to have one).
when you call $(".delete-executor").on('click' you are calling it on the currently existing elements.
adding another .delete-executor later will not add the event to that new element automatically.
but, you can change that to $("#executorsSection").on('click', '.delete-executor', instead. now the event is on the container instead of the element itself.