javascripthtmljqueryjquery-eventsdynamic-data

Dynamically Adding Elements and trying to use the selectors .click event jQuery


I'm trying to dynamically add elements and have click listeners for them in JQuery. For whatever reason the removeGroup event does not get set off when I click on an elements 'remove' button. Any help would be great.

$('.removeGroup').click(function(event){
    alert();
});
               
cartPopper.click(function(event){
    $('#selectedGroupList').find('.selected').remove();
    for(group in selectedGroups)
    {
        var group_id = selectedGroups[group];
        var name = $('.' + group_id).text();
        $('#selectedGroupList')
            .append
            (
            '<li style="font-size:20px" class="selected ' + group_id + '">'
            + '<a href="javascript: void(0);" class="">'
            + '<button class="btn btn-danger removeGroup" type="button">'
            + 'Remove'
            + '<text class="groupValue" style="display: none;">'
            + group_id + '</text></button></a>'
            + name
            + '</li>'
            );
     }
     cartPop.show();
});

Solution

  • In laymans terms, the code which you have written only binds a click event to elements that already exist and doesnt bind it to newly created elements.

    By using the event delegation model, you can make it bind to current and future elements. I think I'm really bad at explaining so please refer to delegate() and on for more information.

    Replace

    $('.removeGroup').click(function(event){
        alert();
    });
    

    With

    $(document).on('click', '.removeGroup', function(event){
        alert();
    });