0

I append a button which shows an alert but I can't see alert when I click the button. How Can I fix this?

<!doctype html>
<html>
<head>
<title>test</title>
<meta charset="UTF-8">
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function() {
    $("#myButton").on('click', function() {
          $("<h1>Hello</h1><input id=\"but\" type=\"button\">Click").appendTo("#main_body"); 
    });
    $( "#but" ).on( "click", function() {
        alert( "bla bla" );
    });    
});   
</script> 
</head>

<body id="main_body"> 
    <input type="button" value="Tıkla" id="myButton" />
</body>
</html>
Yusuf ÇAKIRCA
  • 161
  • 1
  • 3
  • 15
  • 1
    Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – freedomn-m Jun 29 '17 at 13:56

3 Answers3

3

You are adding a listener and then adding the input to the DOM. Click event must be binded after the append, to be able to link it to input.

$(document).ready(function() {
    $("#myButton").on('click', function() {
          $("<h1>Hello</h1><input id=\"but\" type=\"button\">Click").appendTo("#main_body"); 
          $( "#but" ).on( "click", function() {
            alert( "bla bla" );
          });  
    });

});   
tech2017
  • 1,806
  • 1
  • 13
  • 15
2

You can't do that! You have to delegate

$(document).ready(function() {
    $("#myButton").on('click', function() {
          $("<h1>Hello</h1><input id=\"but\" type=\"button\">Click").appendTo("#main_body"); 
    });  
}); 
$(document).on( "click", "#but", function() {
        alert( "bla bla" );
});  
Sampgun
  • 2,822
  • 1
  • 21
  • 38
2

Call the second onclick function within the same function you created the second button. That will work my good sir.

$(document).ready(function() {
    $("#myButton").on('click', function() {
          $("<h1>Hello</h1><input id=\"but\" type=\"button\" value=\"But\">Click").appendTo("#main_body"); 
            $( "#but" ).on( 'click', function() {
                alert( "bla bla" );
            });    
    });
});       
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<!doctype html>
<html>
<head>
<title>test</title>
<meta charset="UTF-8">
</head>

<body id="main_body"> 
    <input type="button" value="Tıkla" id="myButton" />
</body>
</html>
Sam
  • 2,856
  • 3
  • 18
  • 29