0

My page has a button and when it is clicked it is to create another button on that page which will trigger an alert box when clicked. Although, it seems as if the DOM is ignoring the on click event. Can someone shed some light? Thanks.

<div class="myDiv"></div>


Click Me!

$("#btnSub").on("click", function(){
$('<p>This will append to myDiv</p><br><button id="btnAfter">After button</button>').appendTo(".myDiv");
$('#btnSub').remove();

});

$("#btnAfter").on('click', function(){
    alert("test");
});

JSFiddle : http://jsfiddle.net/jpavlov/fbojv76t/

Alex Char
  • 32,879
  • 9
  • 49
  • 70
jpavlov
  • 2,215
  • 9
  • 43
  • 58

3 Answers3

4

You will need event delegation for attaching events to dynamically added elements.

$(".myDiv").on('click','#btnAfter', function(){
  alert("test");
});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1

Try using jQuery() to add click event when jQuery object created , .add()

$("#btnSub").on("click", function () {
    var button = $("<button />", {
        id: "btnAfter",
        html: "After button",
        on: {
            "click": function () {
                alert("test");
            }
        }
    });
    $("<p>This will append to myDiv</p><br>")
    .add(button)
    .appendTo(".myDiv");
    $("#btnSub").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div class="myDiv"></div>
<br>
<button id="btnSub">Click Me!</button>
guest271314
  • 1
  • 15
  • 104
  • 177
1

This is because the button #btnAfter does not exist when you add the event handler.

In a case like this you should use delegated event handler. You put the event handler on the existing parent ('.myDiv'), and provide a selector as second argument ('#btnAfter').

Try this in you fiddle:

$(".myDiv").on('click','#btnAfter', function(){
   alert("test");
});

jQuert documentation for on() - Direct and Delegated events

J.G.Sebring
  • 5,934
  • 1
  • 31
  • 42