Unable to retrieve correct target value in Rails app

I am building a simple shopping cart app and using Stimulus JS to handle the interaction between the Rails views and Javascript logic.

In the Cart page, I am displaying the product by looping through them in the UI as:


<% @curr_cart.items.each do |item| %>

     <span id="test" data-target="cart.count">

        <%= item.quantity %>

     </span>

I am trying to add a ‘delete’ functionality that removes items from the cart. My removal logic works fine but I am unable to update the quantity of the right item. Every time I remove a product, only the first item’s quantity gets decremented.

This is how I’m updating:

this.countTarget.innerHTML = Number(this.countTarget.innerHTML)- 1;

Tried using values and data attributes but no luck :frowning:

Spent most of today, trying to figure this out but wasn’t able to. Any idea or suggestions on how this can be fixed?
Thanks!

Have you tried using this.countTargets (plural)?

You could loop through those and make whatever changes you need. For example:

this.countTargets.forEach((targetElement) => ...)