'How to Give List of Objects IDs and add a click event based on each List IDs in Django

Here in my Django code, I have a list of prices. Now I gave them unique IDs which works well, but when I try to add a click event, the click event only works for only one list item continuously.

      {% for price in logistic_branch_pricing %}
      <h1 id="select-delivery-location-{{price.id}}" 
   onclick="calculateDeliveryPrice()">{{ price.id }}-{{price.small_kg_price}}
      </h1>
      
      {% endfor %}

   {% for price in logistic_branch_pricing %}
   <script>
    function calculateDeliveryPrice() {
      var omo = document.getElementById("select-delivery-location-{{ price.id }}")
      omo.classList.add('d-none')
      console.log(omo)
    }
  </script>
   {% endfor %}


Solution 1:[1]

You don't have to add loop over your <script> tag just pass event keyword inside your javascript onclick function like this

{% for price in logistic_branch_pricing %}
   <h1 id="select-delivery-location-{{price.id}}" onclick="calculateDeliveryPrice(event)">{{ price.id }}-{{price.small_kg_price}}
   </h1>
{% endfor %}

and inside your javascript do like this

<script>
  function calculateDeliveryPrice(e) {
      var omo = e.target
      omo.classList.add('d-none')
      var small_kg_price = omo.textContent.split('-')[1] // return small_kg_price
      console.log(omo) // returns element
      console.log(omo.id) // returns id of element
  }
</script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1