Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing dynamically inserted html with jQuery

I'm trying to dynamically create and remove items from a list, it works just fine... sort of, I can remove items, and create items, but once an item has been created, I cannot remove it again, but I can remove the items present when the page loads.

Here is my code

<div class="list">
    <div class="item">
        <input type="text" value="" />
        <a href="" class="removeitem">Remove this item</a>
    </div>
    <div class="item">
        <input type="text" value="" />
        <a href="" class="removeitem">Remove this item</a>
    </div>
    <a href="" class="additem">Add item to list</a>
</div>

<script type="text/javascript">
// Add item to list
$('.additem').click(function(){
    var template = $($(this).prev().get(0)).clone();
    template.insertBefore($(this));
    return false;
});

// Remove item from list
$('.removeitem').click(function(){
    $(this).prev().parent().remove();
    return false;
});
</script>

I can remove the 2 original items, but when I create new ones, they cannot be removed

like image 530
kristian nissen Avatar asked Apr 23 '26 22:04

kristian nissen


1 Answers

You need to use live events rather than the normal style you are using at the moment.

The click events are bound on load, at which point only the original items are present to be bound.

You would use live events like this:

<script type="text/javascript">
// Add item to list
$('.additem').click(function(){
    var template = $($(this).prev().get(0)).clone();
    template.insertBefore($(this));
    return false;
});

// Remove item from list
$('.removeitem').live("click", function(){
    $(this).prev().parent().remove();
    return false;
});
</script>

There is an overhead to using live events (it has to monitor all events in the DOM and check if they match I believe). Therefore, only use them when necessary.

like image 179
Garry Shutler Avatar answered Apr 25 '26 10:04

Garry Shutler



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!