┼Żygimantas Pranka ┼Żygimantas Pranka - 7 months ago 39
Javascript Question

Only first button works in forEach tag with Jquery

So I ran into a small problem... I have a forEach tag and in it there is a button. The button is connected to a JS which loads another .JSP file. However it seems that only first button works if I connect the JS to the buttons id

$("#imageshow").click
like so, but if I use
$("button").click
it works fine. Despite being able to make it work I have too many buttons in the .JSP file to use it this way. So I would appreciate you help in this matter :)

The .JSP file:

<c:forEach var="building" items="${buildings}" >
<button id="imageshow" class="btn btn-default btn-xs" data-toggle="modal" data-target="#myModal" value="${building.getBuildingID()}">View</button>
</c:forEach>


This is the JS

$("#imageshow").click(function() {
var id = $(this).attr("value");
$("#imgas").load("SlideShow.jsp?id=" + id);
});

Answer

The id attribute should always have a unique value, which is currently not the case. Try using class instead (and querying as .imageshow.