0

I am trying to dynamically add delete buttons with each row, with value corresponding to the id in the sql database after making an xmlHttp request. I am able to retrieve the data from sql database and output it how I want. However, I want to include a delete button next to each result to delete them in case user wants, however when I use : document.getElementById("delete-btn").addEventListener("click", deleteContact, true); it gives me an error "document.getElementById(...) is null". I have made two different script files and included them inside the page in correct order. How can I fix it?

delete.js

document.addEventListener('load', showAddressBook, true);

function showAddressBook(){

var xhr = new XMLHttpRequest();

xhr.open('GET', 'getAddress.php', true);

xhr.onreadystatechange = function() {
    if(this.readyState == 4 && this.status == 200){
        //do somethiung
        var users = JSON.parse(this.responseText);

        console.log(users);
        var output = "";

        for (var i in users){
            output += 
            '<tr class="table-active">'+
            '<td id="delete-firstName" value="" >' + users[i].firstName+ '</td>'+
            '<td>' + users[i].lastName+ '</td>'+
            '<td id="delete-phoneNumber">' + users[i].phoneNumber+ '</td>'+
            '<td>' + users[i].email+ '</td>'+
            '<td>' + users[i].type+ '</td>'+
            '<td> <button type="button" class="btn btn-danger" id="delete-btn" value="' + users[i].id +'">Delete</button> </td>' +
            '</tr>';
        }

        document.getElementById("deleteTable").innerHTML = output;
    }
}

xhr.send();

}

delete2.js

document.getElementById("delete-btn").addEventListener("click", deleteContact, true);

    function deleteContact(){
     //do something
    }
  • That's because of asynchronousness. There's no button by the time you call getElementById. You have to make sure that the onreadystatechange callback calls first and try to search the button only then. – vitkarpov May 15 '20 at 06:02
  • The answer to your question will be found here - https://stackoverflow.com/questions/34896106/attach-event-to-dynamic-elements-in-javascript – Lewis Lockhart May 15 '20 at 06:03
  • Thanks @LewisLockhart was able to resolve my issue using the article you shared! – Talha Kiani May 15 '20 at 06:24

0 Answers0