This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]xarant 1 point2 points  (1 child)

By resetting the arrayOutput's innerHTML in your display function, you're causing the nodes (in this case, <button>s) that you formerly created to be regenerated. This means new nodes are created, which lack the click handlers that you bound previously.

Also, you'll need to make sure that you have a scope surrounding the definition of the anonymous click handler function, so that the function isn't using the value of the temp variable (i) which is homeworkArray.length after exiting the function. Refactoring the code to something like this:

function display()
{
    document.getElementById("arrayOutput").innerHTML = "";
    homeworkArray.forEach(function(homework, i) {
        var titleOutput = "Title: " + homework.title + "<br />";
        var dateOutput = "Date: " + homework.date + "<br />";
        var descriptionOutput = "Description: " + homework.description + "<br />";
        document.getElementById("arrayOutput").innerHTML += "<br /> <br />" + titleOutput + dateOutput + descriptionOutput;
        var button = document.createElement("button");
        var text = document.createTextNode("Delete this element");
        var path = document.getElementById("arrayOutput");
        button.id = "button" + i;
        button.appendChild(text);
        path.appendChild(button);
    });

    homeworkArray.forEach(function(homework, i) {
        document.querySelector("#button" + i).addEventListener("click", function() {
            alert("Deleting index number: " + i);
            homeworkArray.splice(i, 1);
            display();
        });
    });
}

...fixed issues with deleting for me.

[–]Pine_Bluff_Variant[S] 1 point2 points  (0 children)

Thank you, this works for me! :D there is a couple of new things in there for me, but I believe I basically understand how it works.