0

I have a problem. First I have this code with which I can generate a new element. This code as such is working fine.

$(document).ready(
    function() {
        $( ".addto" ).click(function() {
        var text = $(this).children(".textlink").text();
        html = '<li class="ui-state-default"><a href="#" class="delete"><i class="fa fa-trash" aria-hidden="true"></i></a> <span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' + text + '</li>';
        $( "#sortable" ).append( html );
        });
});

If you can see, this code generates an html which is apended in the div "#sortable". That works fine. But not the next step: this code has a trash can icon, whose intention is when you click on it, you can delete the element. If I write this code in plain HTML it works, but when it comes about the html generated by jQuery, it doesn't work. This is the code i'm using to remove the elements.

$(document).ready(
    function() {
        $( ".delete" ).click(function() {
        $(this).parent().remove();
        });
});

Thanks

2 Answers2

0

I would add the listener to the document so it catches even not-yet-existing elements.

$(document).on('click', '.delete', function(e){
$(this).parent().remove();
})
itamar
  • 3,837
  • 5
  • 35
  • 60
-1

When you're assigning the event handler, there are no elements to bind to. You're adding them later.

You'll have to bind the event to a container element, and use deferred events.

$('#container').on('click', '.delete', function() {
    // do delete stuff here
});
HoofHarted
  • 176
  • 2
  • 5