Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 469
Eilidh Avatar asked Dec 06 '25 04:12

Eilidh


1 Answers

Try this - (You need to use event delegation)

$("#poolofobjects").on('click',".selected_object",function(){
  $(this).closest("td").remove();
});
  • http://api.jquery.com/on/
  • http://learn.jquery.com/events/event-delegation/
like image 165
Mohammad Adil Avatar answered Dec 07 '25 20:12

Mohammad Adil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!