0

I am trying to create a simple todo app that posts new items and appends to the DOM and removes the item when it is clicked on. I am able to get todo-items to append to the page but they are not being removed when they get clicked on. I beleive it has something to do with my onclick event handler as it is not selecting the "li" properly. Any thoughts?

heres the code:

<html>
<head>
    <script src='jquery-2.1.3.js'></script>
    <script src='handlebars-v2.0.0.js'></script>
</head>
<body>


        <!-- #TODO LIST
        Create textarea "todo item" and associated "submit button"
        When "submit button" is clicked
            take data entered into "todo item"
            append to empty div "todos" as Li item with id of the todo item
            Empty the "todo item"
        When a list item in "todos" is clicked delete item from "todos"
        -->


        <div>
            <textarea id = 'todoItem'></textarea>
            <button id = 'submitButton'>Post</button>
        </div>

        <div class = 'todos'>Items</div>

        <script>
            $("#submitButton").on("click", function(){
                var todo = $("#todoItem").val();
                $('<li>' + todo + '</li>').appendTo('.todos');
                $("#todoItem").val('');
            });
            $("li").on("click", function(){
                $('li').remove();
            });
        </script>
    </body>
    </html>
rahul2001
  • 1,207
  • 1
  • 15
  • 26

1 Answers1

0

There are a few issues here:

  1. You don't have a click event on button to submit the entered text
  2. $("li").on("click", function(){ won't work because the li is being appended after the DOM loads so you need to add an event listener somewhere else (like the body) and add the li as a delegation..ex: $("body").on("click", "li", function(){
  3. you should call $(this).remove(); instead of $("li").remove() to remove the li that is actually clicked on

FIDDLE

$("#submitButton").click(function(){
   var todo = $("#todoItem").val();
   $('<li>' + todo + '</li>').appendTo('.todos');
   $("#todoItem").val('');
});


$("body").on("click", "li", function(){
   $(this).remove();
});
jmore009
  • 12,570
  • 1
  • 17
  • 33