Calimera
Calimera

Reputation: 145

Javascript Delete Entry Array Button OnClick

I am currently trying to delete entries from my local storage list (array) with delete buttons next to each line. I made the function to delete it, and also the function that adds the button / each line in general. It looks like this:

function printData() {
    let output,
        i;
    let element;

    output = "";
    for(i=0; i<commentsData.length; i++) {

        // adding the delete button to each entry:
        element = "<em id='i'>"+commentsData[i].date+"</em> -- " +
            commentsData[i].contents + "<button id='delete' onclick='deleteEntry()'>Delete</button>" + "<br>";

        output += element;

    }

    $("#comments").html(output);
}

And this is my delete function:

function deleteEntry() {

    alert("Test");
    if (commentsData.length > 0) {
        commentsData.splice(commentsData.indexOf($(this)),1);
    }

    printData();
}

I also tried calling it in my init function:

    function init() {
    loadData();
    printData();

    $("#delete").click(deleteEntry);

};  

But currently it is not working when i click the buttons. What could be the reason for that? I am not yet sure if my deleteEntry is working right now, but my problem is that the clicking of the buttons does not work. You dont need to fix my deleteEntry method - i will do that myself, i just need your help to get my buttons to work please, i would be very greatful! :)

Upvotes: 0

Views: 149

Answers (2)

Tushar Shukla
Tushar Shukla

Reputation: 6615

$("#delete").click(deleteEntry); would work for those elements which are already present on DOM but not for those which are being created dynamically.

You need to bind these elements and yes, as others mentioned, IDs should be unique hence you should use class.

$(document).on('click', '.myDelButton', function() {
    deleteEntry();
});


I think this should work, let me know if not.

Upvotes: 2

Aniruddha Gohad
Aniruddha Gohad

Reputation: 253

ids should always be unique. in your for loop :

 element = "<em id='"+i+"'>"+commentsData[i].date+"</em> -- " +
        commentsData[i].contents + "<button class='deleteBtn'>Delete</button>" + "<br>";

and in your init function :

$("body").on('click', '.deleteBtn', deleteEntry);

Upvotes: 0

Related Questions