EZDC
EZDC

Reputation: 682

Jquery Multiple instances of an event on same page

I am working on a page that has functionality that duplicates a search block. I need to be able to remove these additional search blocks as well. I have a link that has a click event attached to it in order to remove it. This seems to work on the first instance but every duplicated instance after it doesn't seem to want to work.

Any explanation of why this isn't working? I'm still fairly new with jquery.

This is the code:

$('.k-item').click(function(){

        var $searchblock = $('#search-block').html();
        var $addsearchblock = '<div class="additional-search-block"></div>';
        $('.additional-search-block').html($searchblock).attr('class', 'added-search').append($addsearchblock);
    });

$('.remove').click(function(e){
                e.preventDefault();
                //alert('hello');
                $(this).parent().hide();
            });

This is the page I am working on:

http://www.mniac.com/ELRN5/search-template.html

Upvotes: 0

Views: 774

Answers (2)

jmoerdyk
jmoerdyk

Reputation: 5519

When you bind using .click() and the like, it only binds to elements present in the DOM at the time the binding is made. You need to use .on() with delegated events if you want them to work on dynamically added elements.

$(document).on('click', '.remove', function(e){
    e.preventDefault();
    $(this).parent().hide();
});

If you have a parent element that closer to all the target elements than document then you should bind to that element instead. Given your example page:

$('#content').on('click', '.remove', function(e){
    e.preventDefault();
    $(this).parent().hide();
});

Upvotes: 1

Michael Malinovskij
Michael Malinovskij

Reputation: 1422

If you need a fish then use:

$('<selector of parent of elements you want to attach events to>').on('click', '.remove', function(e) {
    e.preventDefault();
    $(this).parent().hide();
})

If you need a fishing rod then read about event delegation.

Upvotes: 1

Related Questions