Home > Blockchain >  Adding delete button functionality to a button which have same class name. (JavaScript, jQuery)
Adding delete button functionality to a button which have same class name. (JavaScript, jQuery)

Time:12-01

I am working on small functionality and facing an issue regarding delete buttons that are dynamically added along with card div and have the same class name in each button.

on writing :

$(".delete-button").on('click', function(e){
    e.preventDefault();
    $(this).parent('div .card').remove();   
});

This code runs only for the first card div button.

And, clicking on the other card's delete button is not working.

Here is the JSFiddle link for getting a clear image of my code.

Dynamic cards

As you can see there are two cards in the image. So, on click of card 2's delete button, it should delete card two.

CodePudding user response:

Using your Fiddle, consider this:

https://jsfiddle.net/Twisty/cxtm7uzd/

JavaScript

  $(".main-container").on("click", ".delete-button", function(e) {
    e.preventDefault();
    if (confirm("Are you sure you wish to delete this card?")) {
      $(this).closest(".card").remove();
      itemCounter--;
    }
  });

This delegates the Event properly.

Delegated event handlers have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated event handlers to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

  • Related