Eilidh
Eilidh

Reputation: 1374

How can I remove() an object after appending it to the page?

I'm trying to use jQuery to allow a user to specify a pool of objects which they can then remove.

I want the user to be able to click on the list of objects to add them to the pool, and if they wish to remove any objects from the pool, click on the objects in the pool to do so.

$(document).ready(function() {
    $('.object').click(function() {
        var typeOfObject = $(this).attr('id'); 
        $('#poolofobjects').append('<td><div class="selected_object">' + typeOfObject + '</div></td>');
    });
    $('.selected_object').click(function() {
        $(this).remove();
    }); 
});

Adding an object to the pool of objects works fine, however I cannot seem to remove an object which has been added to the pool.

Upvotes: 3

Views: 88

Answers (3)

Cem Demir
Cem Demir

Reputation: 142

This code is running, maybe you want deleted td tags of selected_objects. You can try this code;

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

Upvotes: 0

tilleryj
tilleryj

Reputation: 14379

It's because the object doesn't exist in the page yet when your selector runs, so the event handler isn't added to it.

Use on() instead - http://api.jquery.com/on/

Upvotes: 1

Adil Shaikh
Adil Shaikh

Reputation: 44740

Try this - (You need to use event delegation)

$("#poolofobjects").on('click',".selected_object",function(){
  $(this).closest("td").remove();
});

Upvotes: 4

Related Questions