You are viewing limited content. For full access, please sign in.

Question

Question

Need help triggering a "delete" item from a collection

asked on November 22, 2017 Show version history

Good morning,

I'm running into an issue where I want to trigger an event when the X for deleting an item in a collection is clicked. I have a simple collection with only one field in it, for testing purposes.

When I click "Add" the alert "test add" is displayed as expected. This happens as many times as I click it. However, when I click the X for deleting an item, only the "test remove" alert shows if I click on the first top item on the list. If I try to delete anything from the bottom or middle, I don't get the "test remove" triggered. 

Is there something that I need to adjust to make it work so that it triggers the "test remove" alert from any X clicked?

$( document ).ready(function() {
  
  $('.cf-collection-append').click(function(){

	alert('test add');


  });
  
  
    $('.cf-collection-delete').click(function(){
      
      alert('test remove');

  });
  
});

Thank you,

Raul Gonzalez

collectionRemove.PNG
1 0

Replies

replied on December 7, 2017

Hi Raul,

The script runs on document ready, and when form load, there is only delete button on the first row so your click event was registered on that one only.

When you add a new row, the new delete button has no click alert event.

To make it work, you could either re-register the click event when adding new rows, or register the event to a parent element that exists on form load (like the collection).

0 0
replied on February 21, 2023

I know this is old, stumbled on it, but a much more elegant solution is to put your listener on a parent element of a dynamic one and refer to the dynamic element in a second parameter of the "on" function in this case.   I used document as my parent and of course the collection as my second parameter. 

$(document).on('click','.cf-collection-delete',function(){
   //do your stuff here
}) 

 

0 0
You are not allowed to follow up in this post.

Sign in to reply to this post.