0

I cant get an alert to trigger when a dynamicaly generated button is clicked?

The alert is not going to be the final function but was a test to make sure the trigger is working correctly.

I tried a "onclick" function as a trigger and used the id as a jquery trigger so not sure why it would not work, I will add a snippet below that shows what I mean.

any pointers would be much appreciated as I am sure it is something simple I am missing.

From the file that generates and displays the button(it displays ok)

var modOptsMsg = document.getElementById("modOptionsMessage").value + '<input type="button" id="removePost" onclick="removePost()" value="Remove Post"/>';

$("#modOptsShowMsg").empty().append(modOptsMsg);

Neither of these simple tests work js or jquery

function removePost(){
    alert("alert");
}
$('#removePost').click(function(){
    alert("alert");
});

Thanks in advance.

akaBase
  • 2,098
  • 1
  • 15
  • 30
  • 1
    Before question is closed as duplicate: it should be `$(document).on("click", '#removePost', function() { alert("alert"); });` – Regent Sep 11 '14 at 16:40
  • @regent thank you! i knew i had just been looking at it to long and as for duplicate i only posted it once? – akaBase Sep 11 '14 at 16:44
  • @Parody you're welcome. You asked once. But this question is asked by different people many times per each day :) – Regent Sep 11 '14 at 16:45
  • 2
    @JayBlanchard should pick appropriate duplicate that isn't 4 years old and predates `on()` – charlietfl Sep 11 '14 at 16:50

2 Answers2

1

As @Regent has pointed out in the comments, use:

$(document).on("click", '#removePost', function() { 
    alert("alert"); 
});
PeterKA
  • 22,910
  • 4
  • 23
  • 48
-2
  $('#modOptsShowMsg').on("click", '#removePost', function() { 
   alert("alert"); 
});

the above code will work..if jquery is lesser than 1.7 use .live() instead of .on()

Raja Sekar
  • 1,984
  • 14
  • 23