Eli Nahon
Eli Nahon

Reputation: 29

jQuery - removing an element by its class that was previously cloned

below is my code. the last bit of code is the part that isn't working.

I am using jQuery to populate a table of data from an array of objects:

// loop to populate table data
for (var i =0; i <= numItems-1; i++) {
    var newItem = '<tr id="item_' + (i+1) + '"><td>' + items[i].name +
'</td>' + '<td>$' + items[i].price + '</td>' + '<td>' + items[i].category + 
'</td>' + '<td>' + items[i].type + '</td>' + '<td>' + items[i].modelNumber +
'</td></tr>';
    $('#itemData').append(newItem);
};

then, I tell jQuery to clone the element that has been clicked, adding a class (cartItem) to the element so that I can remove it later if the user clicks on it. i place it in another element whose ID is cartData (i'm not sure if I'm doing this in an efficient way)

for (var i=0; i<= numItems-1; i++) {
    $('#itemData #item_' + (i+1)).click(function () {
        $(this).clone().addClass('cartItem').appendTo('#cartData');
    });
};

i'm using this code to remove the element.

$('.cartItem').click(function () {
    $(this).remove();
});

Upvotes: 0

Views: 445

Answers (1)

adeneo
adeneo

Reputation: 318182

On dynamic elements you need delegated event handlers:

$('#cartData').on('click', '.cartItem', function () {
    $(this).remove();
});

Upvotes: 2

Related Questions