-1

See this screenshot. I have a list of things to bring to college. I have a text input with an add button. When you type something into the input and click add, it gets added. However, when I click the close button of the item that got added, it doesn't work. The alert('test') also doesn't show up, so I guess that the new close icon isn't responding to clicks. How can I get it to work? Here's my code:

Javascript

  $("#packing_list_css .close").click(function() {
    $(this).closest('li').hide();
    alert('test');
  });
  $("#everyday_ul button").click(function() {
    new_item = $("#everyday_ul :text").val();
    new_item.trim();
    if (new_item.length != 0)
      $("<li><span class=\"close\">&times;</span>" + new_item + "</li>").insertBefore( "#everyday_ul :text" );
  });

HTML

<p>Everyday</p>
<ul id="everyday_ul">
  <% everyday.each do |item| %>
    <li><span class="close">&times;</span> <%= item %></li>
  <% end %>
  <input type="text"><button class="btn btn-link">Add</button>

Adam Zerner
  • 17,797
  • 15
  • 90
  • 156

1 Answers1

2

Because you:

  1. Get all the elements that match #packing_list_css .close in the document
  2. Bind an event handler to each of them
  3. Add a new element that matches that selector

The new element didn't exist for steps 1 and 2 so it never gets an event handler bound to it.

Bind the event handler to #packing_list_css, let the click event bubble up to it, and check to see what was actually clicked.

$("#packing_list_css").on("click", ".close", function() {
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335