javascript - jQuery $(this).attr ('data-id') -
i have jsp file wich display products, product class entity, , shopping cart written in js. in jsp have foreach added button, works first product others don't work @ all.
what wrote wrong? problem on jsp or in js?
jsp page
<c:foreach items="${produkt}" var="produkt"> <div class="produkt-container" style=" border: 1px solid #ccc; padding: 5px; width: 300px; margin: 10px ; display: inline-block;text-align:left;"> <a href="produkt${produkt.id}" >${produkt.model}</a> <%--<img src="${produkt.images[o]}" alt="">--%> <c:foreach items="${produkt.images}" var="image"> <img src="${image}" alt="" style="border: 1px solid black; width: 260px"> </c:foreach> <button id="buttonaddtocart" data-art="${produkt.id}" style="margin: 5px; position: relative"> add cart </button> </div>
js page
console.log("test"); var cart = {}; $("#buttonaddtocart").click(function () { var produktidforcart = $(this).attr('data-art'); if (cart[produktidforcart] != null) { cart[produktidforcart]++; } else { cart[produktidforcart] = 1; } console.log(cart); });
an important note:- id's
need unique per element.so ask use class
instead of id
there below:-
<button class="buttonaddtocart" data-art="${produkt.id}" >
and change jquery code below:-
$(".buttonaddtocart").on('click',function(){ var produktidforcart = $(this).data('art');//prefer use .data //...rest code
reference:- when better use .data() or .attr()?
in case if these buttons created dynamically use jquery event-delegation:-
$(document).on('click',".buttonaddtocart",function(){ var produktidforcart = $(this).data('art');//prefer use .data //...rest code
Comments
Post a Comment