-3

In my jQuery, I add a series of li elements, and each li element has a button that is a child element. What I'm trying to do is make a click event handler to attach to the button, that will remove both the button and it's parent li element, when clicked. This is my HTML:

        <div id="empty_message" class="open">
            <h3>You have no tasks left to accomplish!</h3>
        </div>
        <div id="tasklist">
            <ol class="list" id="list">  
            </ol>
        </div>

This is the jQuery I wrote:

$("#add_task").click(function() {            
        //create a li, save input in there, and add to ol
        var new_task = $('<li></li>');
        new_task.text($("#add_todo").val());
        //new_task.attr('id', 'new_task');
        new_task.appendTo('ol.list');

        if (new_task)
        //create button and attach it to new li element
        var new_button = $('<input />').addClass('done');
        new_button.attr({
            type : "button",
            value : "Task Accomplished!"
        });
        new_button.appendTo(new_task);

    }

    $("#add_todo").val("").focus();

});
//end click event of Add task button

$('.done[value="Task Accomplished!"]').click(function() {
    $(function () {
        alert("This is working.");
    });
    //hide <li> element
    $(this).parentElement.remove();

    //if list is empty, show empty message
    if ($("#list li").length == 0)
        $("#empty_message").show();

    $("#add_todo").focus();
});
//end click event of Task Accomplished button

The Add Task button (first function) is working. I can't figure out why the Task Accomplished button won't work!! Can anyone help me out?

Meg
  • 32
  • 1
  • 6

1 Answers1

0
$("#add_task").on('click', function() {            
    //create a li, save input in there, and add to ol
    var new_task = $('<li />', {
        text : $("#add_todo").val()
    });

    var new_button = $('<input />', {
        'class' : 'done',
        type    : 'button',
        value   : 'Task Accomplished!',
        on      : {
            click : function() {
                $(this).closest('li').remove();
                if ($("#list li").length == 0) {
                    $("#empty_message").show();
                }
                $("#add_todo").focus();
            }
        }
    });

    $('#list').append(new_task.append(new_button));
    $("#add_todo").val("").focus();
});

Create the event handlers as you create the elements, and use closest instead of parentElement.

adeneo
  • 293,187
  • 26
  • 361
  • 361