0

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();
    });
  });
});
2
  • 1
    It seems that you're using the same ID multiple times. IDs must be unique. Consider using a class instead. Commented Nov 13, 2015 at 21:11
  • 1
    IDs must be unique. And when you fix that, use event delegation to bind the click for the remove icon, don't use .each(). Commented Nov 13, 2015 at 21:11

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.