Search code examples
javascriptjquerylistparent

Removing Parent Elements with jQuery


So I'm working on a small web app where the user creates a list and it is formatted and emailed back to them. Anyway, I am having trouble creating a functioning way to delete list items without clearing everything.

Here is a Fiddle http://jsfiddle.net/mRWt6/

The jquery Code to add/delete items

function deleteItem(){
    $(this).closest('div').remove();
}
function addItem(){
    var item = $('#newItem').val();
    $('#list').append('<div><span>'+item+'</span><button class="delete">X</button></div>');
    $('#newItem').val('');
}

$(function() {
    $('.delete').on('click', deleteItem);
    $('#add').on('click', addItem);
});

The first example that I created manually works as intended, but the new items that are added don't work at all. What's going on here? I'm pretty new to Javascript and jQuery so detailed explanations are appreciated!


Solution

  • delegate event to closest static container:

    $('#list').on('click', '.delete', deleteItem);
    

    More info here: http://learn.jquery.com/events/event-delegation/