pass parameter inside dynamically created <div>

Hello!
I have this script which dynamically creates divs. I would like to pass the id to the controller and be able to visualize the booking form after clicking Book button.

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" >
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 += `
<!-- 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;})
}

$('body').on('click', 'bookingBtn', function() {

let hotelId = $(this).data('hotel-id')
console.log("Hotel id is " + hotelId);
fetch('http://localhost:8080/hotels/' + hotelId + '/booking-form', {
method: 'POST'
})
});

do you have a link to the page?

Hi, I am not sure what you mean?

@stormTrooper Maybe you feel you don’t need it, but if you’re going to ask people for help, please format your code in some way so that it’s legible. If you don’t know how to set up your editor for that, then you can use Prettier’s online tool.

Prettiered code:
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 += `
<!-- 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;
    });
}

$("body").on("click", "bookingBtn", function () {
  let hotelId = $(this).data("hotel-id");
  console.log("Hotel id is " + hotelId);
  fetch("http://localhost:8080/hotels/" + hotelId + "/booking-form", {
    method: "POST",
  });
});

Putting aside the mixing of standard DOM methods and jQuery…

how can I get the id and pass it to the crontroller

Since we can’t see the output it’s difficult to tell where your issue is based on this description. Are the generated <div>s not getting a data-hotel-id, or is the bookingBtn click event listener not able to grab them?

1 Like