Click event works only for first element in loop in a Django template

I am looping around a cart dictionary that is in the session and I have defined a product for all the items. When each cart item button is clicked, they are sent via ajax, but only the first item is sent, even though each item has a product id specified.

{% for item in cart %}
<div class="items flex gap-4 bg-white rounded-3xl border p-4 items-center" data-product-id='{{ item.product.id }}'>
#somecode
<button class="increase-item"> + </button>
<button class="decrease-item"> - </button>
</div>
{% endfor %}
  • js

     $(document).ready(function(){
         var increaseBtn = document.querySelector(".increase-item");
         var decreaseBtn = document.querySelector(".decrease-item");
    
         increaseBtn.addEventListener("click", function(){
             var itemId = $(this).closest('.items').data('product-id');
             updateQuantity(itemId, "increase");
         })
    
         decreaseBtn.addEventListener("click", function(){
             var itemId = $(this).closest('.items').data('product-id');
             updateQuantity(itemId, "decrease");
         })
    
         function updateQuantity(id, action){
             $.ajax({
                 type: 'POST',
                 url: '{% url "cart:update_quantity" %}',
                 data: {'id': id, 'action': action, 'csrfmiddlewaretoken': '{{ csrf_token}}'},
                 success: function(data){
                     $("#total-items").text(data.total_items);
             },
         })
     }
     })
    
Вернуться на верх