Error in Django forloop.counter with javascript function

hi everyone, i am using Django for loop in the template to out put some items an i added the {{forloop.counter}} to the id attribute.

{% for item  in products %}
 
<label class=" update-cart">
    <input type="checkbox" id="ref_prod{{forloop.counter}}" onclick="myFunction" >
    <span class="slider round pt-2"></span>
  </label>
 
  <script>
 function myFunction() {
            // Get the checkbox
            var checkBox = document.getElementById("ref_prod{{forloop.counter}}");
            alert(ref_prod{{forloop.counter}})

          } 
 <script>
{% endfor %}

when i tried this no matter the counter number it keeps alerting “ref_prod1”.
i need it to be able to get something like “ref_prod1”., “ref_prod2” “ref_prod3” etc.

Check our HTML, I guess you have multiple declarations of myFunction and the first gets called each time.

I would recommend adding a event listener to the checkbox and then you can use something like e.currentTarget.id to get id of the selected checkbox.

2 Likes

waow, worked like magic. thank you

this is what i did

{% for item  in products %}
 
<label class=" update-cart">
    <input type="checkbox" id="ref_prod{{forloop.counter}}">
    <span class="slider round pt-2"></span>
</label>
 
  <script>
let btn = document.getElementById("ref_prod{{forloop.counter}}");
btn.addEventListener("click", myFunction)
function myFunction(e) {
            // Get the checkbox
            let checkBox = e.currentTarget.id
            alert(checkBox)
          } 
 <script>
{% endfor %}