1

I'm trying to use a button that is printed by .html(). I've tried .find() after searching through this site but the onclick event still seem not detected.

<div id = "div4html">div</div>
<button id="printbtn">printbtn</button>

<script>
$("#printbtn").on( "click", function() {
    $("#div4html").html('<button id ="btntest">btntest</button>');
});

$("#div4html").find("#btntest").on( "click", function() { 
    alert("on click");
});
</script>

while the #btntest onclick doesn't show an alert, the CSS on #btntest works. There is something I don't know about elements that are created dynamically?

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
ivan
  • 13
  • 2
  • Learn [Event Delegation](http://learn.jquery.com/events/event-delegation/) i.e. `$("#div4html").on( "click", "#btntest", function() { ` – Satpal May 10 '17 at 05:50

3 Answers3

1

You can't do this because js don't even for events in newly created content by default.

Here is the way to do it :

$("#div4html").on('click', "#btntest" , function() {
// Your code
}
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Kuu Aku
  • 320
  • 2
  • 6
0

Delegate the event from the body

$("body").on( "click",'#btntest', function() { 
   alert("on click");
});
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
brk
  • 48,835
  • 10
  • 56
  • 78
0

You need to do:-$("#div4html").on( "click", "#btntest", function() {

It's called:- Event Delegation

Example:-

$("#printbtn").on( "click", function() {
  $("#div4html").html('<button id ="btntest">btntest</button>');
});

$("#div4html").on( "click","#btntest", function() { 
  alert("on click");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "div4html">div</div><br>
<button id="printbtn">printbtn</button>
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98