1

I'm having some issues removing list items upon click after using jquery to add the list items. If I had to guess why this is happenings, it's because jquery might be looking at my original HTML document and not the updated one after adding list items? Either way, I can't figure out how to fix it.

Here is my HTML:

<form>
        <div>
            <label for="todo">I need to:</label>
            <input type="text" id="todo" />
        </div>
        <button id ="add" type="button">Add to your to-do list!</button>
</form>
<ul>
</ul>

And my jQuery:

$(document).ready(function() {
    $('#add').click(function() {
        var item = $('#todo')
        $('ul').prepend("<li>"+item.val()+"</li>");
    });
        $('li').click(function() {
        $(this).remove();
    });
});
carc
  • 63
  • 2
  • 8
  • 2
    We could spend all day listing duplicates of this question :) – Barmar Sep 14 '13 at 17:24
  • 1
    Sorry! I promise I searched around - Looking at the possible duplicates, it looks like I just didn't know how to phrase my question correctly – carc Sep 14 '13 at 17:36

1 Answers1

5

Since you trying to add event handlers for dynamically added elements you need to use event delegation

$(document).ready(function() {
    $('#add').click(function() {
        var item = $('#todo')
        $('ul').prepend("<li>"+item.val()+"</li>");
    });
    $('ul').on('click', 'li', function() {
        $(this).remove();
    });
});

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • I added a button to remove a selected item but it won't do. What am I doing wrong? https://jsfiddle.net/17ufszLq/1/ – Kolja Jul 18 '15 at 13:21