首页 > 解决方案 > Jquery: Removing dynamically generated element when modal confirmation button is clicked

问题描述

For example:

<body>

    <div class="container">
      <!-- Generated by ajax -->
      <div class="item" id="item_1">
        <span class="remove-item"></span>
      </div>
      <div class="item" id="item_2">
        <span class="remove-item"></span>
      </div>
    </div>


    <div class="modal" id="removeItemModal">
        <h3>Are you sure you want to remove?</h3>
        <input type="hidden" id= "removeItemIdModalInput">
        <button type="button">Cancel</button>
        <button type="button" id="remove-confirm-btn">Confirm</button>
     </div>

</body>

When clicked on the remove-item class a modal will be shown with two button Confirm and Cancel when user clicks on confirm, remove the whole (parent) item. How can i achieve this?? Here's what i did:

$(document).on("click",".remove-item", function (e) {

        var removeProductId = $(this).closest(".item").attr("id");

        // Setting the value in modal's hidden input
        $("#removeItemIdModalInput").val(removeProductId);

        $("removeItemModal").modal('toggle');

    });

$(document).on("click","#remove-confirm-btn", function (e) {

        var removeProductId = $("#removeItemIdModalInput").val();

        $("removeItemModal").modal('toggle');

        // Removing the container div/item
        $(removeProductId).fadeOut(300,function () { $(this).remove();});


    });

But It's not working. Why? Is there a better approach?

标签: javascriptjquery

解决方案


[EDIT]
TS wants a modal window, this answer provides an alternative


Instead of a modal window, you can use confirm() too.

If that is confirmed, you select the parent of the span, by using parent(), fade that element out, and remove. Just like you already had.

Also note that you use remove-item and remove_item both, I changed it all to remove_item

$(document).on("click", ".remove_item", function(e) {
  if(confirm("Do you want to remove this box")) {
    $(this).parent().fadeOut(300, function () { $(this).remove();});
  }
  return;
});
#item_1, #item_2 {
  border: 1px solid black;
  margin: 2em;
}

.remove_item {
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <!-- Generated by ajax -->
  <div id="item_1">
  Item 1
    <span class="remove_item">remove</span>
  </div>
  <div id="item_2">
  Item 2
    <span class="remove_item">remove</span>
  </div>
</div>


推荐阅读