Moving javascript code and form outside a for loop

Hi, I want to create a popup modal form when someone clicks on delete. I’m trying this thing I got from here : How To Make a Modal Box With CSS and JavaScript (

The problem is that I don’t want to repeat that form and js code on each for loop item, I want it outside the loop with a unique product pk or id on each click

here my html code:

{% extends 'base.html' %}

{% block content %}
<div class="container">
    {% if messages %}
    <ul class="messages">
        {% for message in messages %}
        <li {% if message.tags %} class=" {{ message.tags }} " {% endif %}> {{ message }} </li>
        {% endfor %}
    {% endif %}
    <div class="grid-container">
        {% for product in products %}
        <div class="grid-item">
                <img src="{{ product.image_url.url }}" alt="{{ product.title }}">
                <h5>{{ product.title }}</h5>

                <!-- DELETE Trigger/Open The Modal -->
                <button id="myBtn">Open Modal</button>


        <div id="myModal" class="modal">
            <!-- Modal content -->
            <div class="modal-content">

                <span class="close">&times;</span>
                <h1>are you sure you want to delete: "{{product.title}}"؟</h1>
                <form class="form_container" enctype="multipart/form-data" action="{% url 'delete' %}"
                    {% csrf_token %}
                    <label for="pincode">enter your code to delte:</label>
                    <input type="number" id="pincode" name="pincode">
                    <input type="submit" name="Confirm" value="delete">



            var modal = document.getElementById("myModal");

            // Get the button that opens the modal
            var btn = document.getElementById("myBtn");

            // Get the <span> element that closes the modal
            var span = document.getElementsByClassName("close")[0];

            // When the user clicks on the button, open the modal
            btn.onclick = function () {
       = "block";

            // When the user clicks on <span> (x), close the modal
            span.onclick = function () {
       = "none";

            // When the user clicks anywhere outside of the modal, close it
            window.onclick = function (event) {
                if ( == modal) {
           = "none";

        {% endfor %}
{% endblock %}

This is more a JavaScript issue than a Django issue - you may get more & better help in a JavaScript-related forum.

In general, you can add the data elements you’re going to need as custom attributes to the individual elements being rendered, then access them through the this reference for the event handler. This allows you to render one instance of the code and modal box, and update it from your JavaScript on an on-demand basis.

I see , thanks for the tip I’ll try to see what to do I’m very low experienced in javascript