0

I have the following setup for a community website:

<div id="posts">
    <div class="container">
        <div id="placeholder"></div>
        <h1>Friend Requests</h1>
    </div>
</div>

getRequests.js appends the following into the container div:

<div id="4" class="result">
    <a href="user.php?id=4">
        <img src="images/user-uploads/profile/?id=4">Random Guy
    </a>
    <div class="response">
    <button data-id="4" class="accept">Accept</button>
    <button data-id="4" class="deny">Deny</button>
    </div>
</div>

friendResponse.js has the following:

$(function(){
  $(".accept").click(function(){
    var id = $(this).attr("data-id");
    $("#"+id).remove();
  });
});

So, you would expect that when I click the accept button, the container with id=1 should get removed, but for some reason, it doesn't.

And also, to add to the peculiarity, the code works if I inject it through the console.

And, for the record, the script is not showing any errors.

Daniyaal Khan
  • 285
  • 1
  • 4
  • 12

1 Answers1

0

Try:

$(function() {
  $(document).on("click", ".accept", function() {
    var id = $(this).data("id");
    $("#"+id).remove();
  });
});

Explanation:

You have to set the event for all new incoming node .accept. You have to bound the event on the document. See live event.

Here is the corresponding jsfiddle

Gnucki
  • 5,043
  • 2
  • 29
  • 44