1

This is the <ul> that holds the list items in the first place:

<ul style="max-width:500px" id="currentRoles" class="list-group">
     <li class="currentRole list-group-item">
            <div class="col-md-6">
                @role.Name
            </div>
            <a href="#" class="linkRemoveRole">Remove This Role</a>
     </li>
</ul>

I remove the list items and append them to new list by using codes below and that works fine:

  $('.linkRemoveRole').click(function (event) {
            var roleName = $(this).siblings().text();
            $(this).parentsUntil('#currentRoles').remove();
            $('#removedRoles').append(
              '<li class="removedRole list-group-item">'
            + '<div class="col-md-6">'
            + roleName
            + '</div>'
            + '<a href="#" class="linkAddRoleBack">Add Item Back</a>'
            + '</li>');
        }); // end of .remove_field click

then I want to get the list items back to where they were by clicking the link that has class "linkAddRoleBack" which has created by codes above:

 $('.linkAddRoleBack').click(function (event) {
            var roleName = $(this).siblings().text();
            $(this).parentsUntil('#removedRoles').remove();

            //$('#currentRoles').append(
               // Irrelevant code...
               );
        });

Here's the problem comes in. All I want to do is remove its parent element while I click the link "Add Role Back" but turns out I can't. I checked the console and it seems like I can't select its parents by

 $(this).parentsUntil('#removedRoles').remove();

but it works fine if I just do this

 $('.linkAddRoleBack').parentsUntil('#removedRoles').remove();

Anybody knows the reason?

zhiyuan
  • 23
  • 5
  • 2
    If you are binding event on dynamic elements use **[event delegation](http://stackoverflow.com/a/30242160/3639582)** - [Reference](https://learn.jquery.com/events/event-delegation/) – Shaunak D May 28 '16 at 11:15
  • Do you define the "add back" click-handler `$('.linkAddRoleBack').click(func...` after you appended the html code? I mean inside / at the end of the remove click handler function ` $('.linkRemoveRole').click(func...`. – Peter Paul Kiefer May 28 '16 at 11:31

1 Answers1

1

Use $(document).on event :

$(document).on('click','.linkAddRoleBack',function (event) {
       var roleName = $(this).siblings().text();
       $(this).parentsUntil('#removedRoles').remove();
});
Dhara Parmar
  • 8,021
  • 1
  • 16
  • 27