I have this script which dynamically creates divs. I would like to pass parameters to the controller and be able to visualize the booking form after clicking Book button. With thymeleaf I would do it like this th:href="@{/hotels/{id}/booking-form(id=*{id})}" however I am not really sure how can I use thymeleaf inside this dynamically created div.
So I tried with javascript, but of course, it is not working so I would really appreciate if someone tells me what I am doing wrong and how can I get the id and pass it to the controller.
<script type="text/javascript" th:inline="javascript">
document.getElementById('showAll').addEventListener('click', showAll);
function showAll() {
fetch('http://localhost:8080/accommodations')
.then(response => {
return response.json()
})
.then((data) => {
let output = `<h2> Search Results </h2>`;
data.forEach(function (hotel) {
output += `
/some divs here/
<!-- Book Now button -->
<div class="d-flex justify-content-end mt-1">
<div class="btn btn-primary text-uppercase" id="bookingBtn" data-hotel-id="' + hotel.id + '" >Book Now</div>
</div>
</div>`;
});
document.getElementById('output').innerHTML = output;
})
}
function booking() {
let hotelId = $(this).data('hotel-id')
fetch('http://localhost:8080/hotels/' + hotelId + '/booking-form', {
method: 'POST'
})
}
document.getElementById('bookingBtn').addEventListener('click', booking);
</script>
When you are using template literals to create a string you can include variables this way ${var}. So in your case you should do data-hotel-id="${hotel.id}"
data.forEach(function(hotel) {
output += `
/some divs here/
<!-- Book Now button -->
<div class="d-flex justify-content-end mt-1">
<div class="btn btn-primary text-uppercase" id="bookingBtn" data-hotel-id="${hotel.id}" >Book Now</div>
</div>
</div>`;
});