user1186050 user1186050 - 3 months ago 13
jQuery Question

OnClick not working with my element

I create an anchor tag and then a

click
event handler, but the event is not triggering. I think the jQuery syntax is incorrect?

var b = '<a class="dz-remove removeAttachment">Remove</a>';
var someOtherElement = $(dropZoneElement).find(".dz-file-preview")[0];
$(someOtherElement).append(b);
$(b).on('click', function() {
dropone.removeAllFiles();
})

Answer

You can't bind an event to a string.

You should bind it to the DOM elements. As you are adding the DOM element after loading the entire document, using 'delegate' helps you.

This should work:

var b = '<a class="dz-remove removeAttachment">Remove</a>';
$(someOtherElement).append(b);
$(someOtherElement).delegate('.removeAttachment', 'click', function() {
  dropone.removeAllFiles();
})