0

I can't get an alert to trigger when a dynamically 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.

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 in JS or jQuery:

function removePost(){
    alert("alert");
}
$('#removePost').click(function(){
    alert("alert");
});
halfer
  • 19,824
  • 17
  • 99
  • 186
akaBase
  • 2,178
  • 1
  • 18
  • 31
  • 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
  • 24,158
  • 5
  • 26
  • 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
  • 2,062
  • 16
  • 23