I have a snippet of jQuery code that adds items to an unordered list when a submit button is clicked. Part of what's added to the list is an "X" button to delete the item from the list. I'm using the each() function to add a click event to every element that gets added to the list, yet it's only attaching to the first element.
Oddly enough, if that event gets fired, and the submit button is clicked again, the next element to be added to the list gets the click event.
Here's the snippet of code:
$("#addTask").click(function() {
if ($("#toDoList").val().trim() != "") {
$("ul.list-group").append("<li class='list-group-item'>" + $("#toDoList").val()
+ " <span class='glyphicon glyphicon-remove' id='removeButton'></span></li>");
$("#toDoList").val("");
};
$.each($("#removeButton"), function() {
$(this).on("click", function() {
$(this).parent().remove();
});
});
});
.each().