0

I am using an API to get various values and for each value creating a button dynamically.

var button_results = document.createElement("button");
button_results.innerText = 'view results';
button_results.value=jobs_data[i]["ID"];
button_results.addEventListener("click", function(){
    getResults(button_results);
}, false);

The button's value holds a job ID using which I have to invoke one API to get the results corresponding to that JOB ID and display in a popup.

async function getResults(btn_result)
    {
        try
            {

                const response = await fetch(
                    'http://10.64.127.94:5000/api/get_results_from_job_id',
                    {
                        method: 'POST',
                        headers: {
                                    'Accept': 'application/json',
                                    'Content-Type': 'application/json',
                                    'Access-Control-Allow-Origin': '*',
                                },
                        body: JSON.stringify({ "job_id": btn_result.value })
                    }
                );
                const jdata = await response.json();
                ldata = jdata["result"]

                document.getElementById("popup_content").innerHTML=ldata;
                const modal = document.querySelector('.modal-wrapper');
                modal.style.display = 'block';
                var close_btn = document.querySelector('.modal-close');
                close_btn.addEventListener('click',hide_popup_in_results);
            }
        catch (err)
        {
            alert(err.message);
            return;
        }
    }

HTML of popup:

 <div class="modal-wrapper">
     <div class="modal">
         <div class="modal-close">X</div>
         <div class="modal-content">
             <span>Results:</span>
             <br>
             <p style="font-size:70%;color:blue;" align="left" id="popup_content"></p>
         </div>
     </div>
 </div>

The problem is that no matter which button I click, it shows the results for the last button created dynamically. Looks like its getting overwritten. Can someone tell me whats wrong here.

Akshay J
  • 5,362
  • 13
  • 68
  • 105
  • You're overwriting the same `var` with each successive button. This looks like a case for [event delegation](https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation#:~:text=Event%20delegation%20is%20handling%20an,that%20matches%20a%20given%20condition.). – pilchard Aug 23 '23 at 08:03
  • thanks, how to accomplish my intention? – Akshay J Aug 23 '23 at 08:03

0 Answers0