-1

Here is the html

<div class="parentDiv">
    <div class="childDiv">
        <!-- here to add button -->
    </div>
</div>

And here is the jquery code :-

$.ajax({
    url : "url.php",
    type : "POST",
    data : {someData : "some data"},
    success : function(data){
        $("#childDiv).html("<button id='clickMe'>Click me</button>");
    }
});

This code not working after element is added through ajax

$("#clickMe").on("click",function(){
    alert("please help!");
});

the #click me is not working.

How can I fix it, make it work ?

ViralP
  • 223
  • 2
  • 7
Soumen Pasari
  • 145
  • 1
  • 2
  • 11

1 Answers1

-1

Because you are creating <button id='clickMe'>Click me</button> only after your asynchronous call returns, the moment you are trying to attach an event handler to it, it's not existent yet. Also, you are trying to attach the button to an element that doesn't exist - you don't have a div#ChildDiv, but it has the CSS class childDiv.

Instead attach the event handler directly after creating it:

$.ajax({
  url : "url.php",
  type : "POST",
  data : {someData : "some data"},
  success : function(data) {
    // create your button in your ASYNCHRONOUSLY
    // executed success handler function
    $(".childDiv").first().html("<button id='clickMe'>Click me</button>");
    // now that it exists, attach the click handler
    $("#clickMe").on("click",function(){
      alert("please help!");
    });
  }
});
// code that appears here will be executed BEFORE the success function!
// (synchronously)
connexo
  • 53,704
  • 14
  • 91
  • 128