-1

i just started using JQuery and i have a problem, regarding adding a click event listener for a dinamically created button.

So when the user click on button number one, my first function simply add a second button into a div. The problem is that using the same method, my listener for the second button is not working. Here is a simple exemple of what I'm trying to do.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    //listener for first button
    $("#button1").click(function(event){
        event.preventDefault();
        $("#newElement").append("<input type='button' id='button2' value='Need listener for this new button'>");
    });

    //listener for the seccond button (problematic one)
    $("#button2").click(function(event){
        event.preventDefault();
        alert("Second button clicked!");
    });
});
</script>
<title>Exemple JQuery</title>
</head>
<body>
    <input type="button" id="button1" value="Add a new button dynamically">
    <div id="newElement">

    </div>
</body>
</html>

Any ideas are very welcome. Thank you

user2271933
  • 491
  • 2
  • 10
  • 25

1 Answers1

2

Delegated event handlers for dynamically inserted elements

$("#newElement").on('click', "#button2", function(event){
    event.preventDefault();
    alert("Second button clicked!");
});
adeneo
  • 312,895
  • 29
  • 395
  • 388