0

I'm making a simple to do list. It's mostly working and finished. When you click on list elements the object gets removed and you can create new list elements through the text input at the bottom. The only problem is the new list elements can't be removed when you click them for some reason.

Here's the code:

http://jsfiddle.net/dnhynh/7psqndwL/20/

$(document).ready(function(){

    $("li").click(function(){
        $(this).remove();
    });

    $("button").click(function(){
        var entry = $("#entry").val();
        $("<li></li>", {
            text: entry
        }).appendTo("#list ul");   
        $("#entry").val("");
    });

});

3 Answers3

0

Since the new li elements are created dynamically you need to use event delegation to register event handlers to these elements

Try this

$("#list ul").on('click','li',function(){
        $(this).remove();
});

DEMO

Sridhar R
  • 20,190
  • 6
  • 38
  • 35
  • 2
    That worked. Much appreciated. Any idea why the above method doesn't work as opposed to this one? – user3317470 Aug 21 '14 at 04:19
  • @user3317470 Your code doesn't work because it initially selects the inital `li`'s and saves them. When they are clicked, they correctly delete. But when a new one is added, the initial `li` selector isn't updated. @SridharR 's code checks all of the current `li`s as well as any new ones. –  Aug 21 '14 at 04:21
  • @user3317470 check update danswer with info.@Eclecticist Thank s :_) – Sridhar R Aug 21 '14 at 04:23
0

Try this:

$("#list").on("click","li",function(){
        $(this).remove();
});

DEMO

Kiran
  • 20,167
  • 11
  • 67
  • 99
0

This is working fine:

$(document).ready(function(){

  $(document).on('click','li',function(){
     $(this).remove();
  });

  $("button").click(function(){
     var entry = $("#entry").val();
     $("<li></li>", {
        text: entry
     }).appendTo("#list ul");   
     $("#entry").val("");
  });

});

Fiddle Link :- http://jsfiddle.net/7psqndwL/29/


OR

 $(document).ready(function(){

  $(document).on('click','#list li',function(){
     $(this).remove();
  });

  $("button").click(function(){
     var entry = $("#entry").val();
     $("<li></li>", {
        text: entry
     }).appendTo("#list ul");   
     $("#entry").val("");
  });

});
Kartikeya Khosla
  • 18,743
  • 8
  • 43
  • 69