-2

I am running through a todo list tutorial for jQuery and I ran into an issue that I cannot figure out. My code looks exactly like what is in the video. I have tried to do this on both Plunker and JSFiddle and was not able to get it to work. Can anyone see what is wrong with this?

Here is my HTML:

<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8" />
    <title></title>
    <link rel="stylesheet" href="style.css" />

  </head>

  <body>
    <h1>Tasks</h1>

    <ul id="todoList">

    </ul>

    <input type="text" id="newText" /><button id="add">Add</button>



    <script data-require="jquery" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
    <script src="script.js"></script>
  </body>

</html>

and my jQuery:

function addListItem() {
  var text = $('#newText').val();
  $('#todoList').append('<li>' + text + ' <button class="delete">Delete</button></li>');
  $('#newText').val('');
}

function deleteItem() {
  $(this).parent().remove();
}

$(function() {
  $('#add').on('click', addListItem);
  $('.delete').on('click', deleteItem);
});
  • `$(".delete")` only selects existing `class="delete"` elements, it doesn't select elements that don't exist yet. – Kevin B Jul 26 '16 at 22:39

1 Answers1

-2

Try this:

$('.delete').on('click', deleteItem); => $('body').on('click', '.delete', deleteItem);

Explain: if you want to link an event to an element that does not yet exist, you must first bind to document.

Alfredo EM
  • 2,029
  • 1
  • 14
  • 16