I have a list of restaurants, and each restaurant has its articles. For each restaurant representation in the list I have a button. By clicking this button, I want to redirect the user to the page with articles of the specific restaurant.
The restaurant list is dynamically generated via jQuery. I tried giving the button an ID with the restaurant name, but whatever button I click, it gives me the name of the first restaurant in the list. Here is the code:
$(document).ready(function() {
var rests = [];
$.get({
url: "/WebProjekat/rest/restaurants",
success: function(restaurants) {
rests = restaurants;
alert("restaurantssss");
alert(restaurants[0].name);
var arrayLength = restaurants.length;
for(var i=0; i < arrayLength; i++) {
$("#restaurantList").append("<div class=\"row\">" +
"<div class=\"card\" style=\"width: 18rem;\">" +
"<img class=\"card-img-top\" src=\"restaurant.jpg\"" +
"alt=\"Card image cap\"><div class=\"card-body\">" +
"<h5 class=\"card-title\">" + restaurants[i].name + "</h5>" +
"<p class=\"card-text\">" + restaurants[i].category + "</p>" +
"<button id=\"" + restaurants[i].name + "\" class=\"btn\">" +
"See articles" + "</button>" + "</div></div></div>");
}
}
})
$("#addRestaurant").click(function(){
window.location.href = "addRestaurants.html";
});
$("#addArticle").click(function(){
window.location.href = "addArticles.html";
});
$("#restaurantList").on('click', '.btn', function() {
//$("")
var id = $("#restaurantList .row .card .card-body .btn").attr("id");
alert(id);
window.location.href = "articles.html?restaurant="+id;
});
})
As you can see in the for loop I give an appropriate ID to every button, and then in the delegate function I access the button through links with the parent. But like I said earlier, whatever button is clicked, the output is the name of the first restaurant in the list. It's possible I am misinterperting how the delegate function works.
Does anyone have any idea why this isn't working? And if this way is dead end, please provide me an alternative solution. Thanks in advance