0

So, I have a page where a div, PDF object, and a button are all being created on-the-fly by javascript. The creation of those page items works great. The button is to function as a remove PDF and is assigned an id of 'removeAttBtn1', 'removeAttBtn2'...etc for each PDF that was added.

The issue I am having though, is that the jQuery selector I'm attempting to use appears to not be triggering the click event function.

The button is defined as follows;

<input class="btn btn-primary" type="button" id="removeAttBtn0" data-id="0" style="float: right; display: inline-block; margin-top: 3px; margin-right: 15px; margin-bottom:10px;" value="Remove Attachment">

And the jQuery selector I am trying to use for this button is;

$('input[id^=removeAttBtn]').click(function() {
  alert('Remove Attachment button was clicked');
});

Am I missing something here as to why the jQuery is not picking up the click event for the associated button?

Thanks!

Skittles
  • 2,866
  • 9
  • 31
  • 37
  • Likely the click listener is being instantiated before the control has been programatically being placed on the page, so it has no targt. Please post code to run that shows the issue – Jonathan Aug 08 '19 at 15:13
  • 1
    If the elements you're trying to add the event handler to do not exist in the DOM when the page loads you need to use a delegated event handler: `$(document).on('click, 'input[id^=removeAttBtn]', function() { ...`. See the duplicate I linked to for more information – Rory McCrossan Aug 08 '19 at 15:14
  • the "on the fly" part might be crucial here. If the buttons are added after you ran the jQuery code to create the event handler, then it will have only assigned events to buttons which existed at that moment in time. Buttons created afterwards cannot be detected. Read the section of https://api.jquery.com/on/ entitled "direct and delegated event handlers" to understand how to resolve this - if you use delegated events, then you can get jQuery to handle events on any item within the delegated area of the page, no matter when it gets added to the DOM – ADyson Aug 08 '19 at 15:15
  • This makes perfect sense! The buttons are all created as a result of someone adding attachments to a form. Therefore, the buttons won't exist until the user basically creates them. So, now the question is, how can I tie the click events of the created buttons to the jQuery selector then? – Skittles Aug 08 '19 at 15:18
  • Thanks to all of you, I just found my answer! – Skittles Aug 08 '19 at 15:23

0 Answers0