Salmononius2
Salmononius2

Reputation: 295

jQuery - click event not being added to every element

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();
    });
  });
});

Upvotes: 0

Views: 611

Answers (1)

j08691
j08691

Reputation: 208040

As I noted in my comment, IDs must be unique, so you need to change removeButton from an ID to a class. Then since you are adding the remove buttons dynamically, you need to add the click handler using .on()'s event delegation syntax. This would be accomplished with:

$("#addTask").click(function () {
    $("ul").append("<li class='list-group-item'>task <span class='glyphicon glyphicon-remove removeButton'>X</span></li>");
})
$('ul').on('click', '.removeButton', function () {
    $(this).parent().remove();
});

jsFiddle example

Upvotes: 3

Related Questions