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! :)
2 Answers 2
$("#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.
3 Comments
docuement if possible.printData() once as a second execution will propagate duplicate ID's in the markup. For a complete answer, address the issues within that function.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);
2 Comments
id='i'> please fix that also to not duplicate the idprintData() once as a second execution will propagate duplicate ID's in the markup.
<emelement for emphasis is OK but perhaps better to style using CSS.deleteEntryhas issues as you note, keeping the display and array or whatevercomments.Datais in sync with each other will be a part of your final solution.