0

Possible Duplicate:
jQuery click not working for dynamically created items

        $(document).ready(function(){
            $('#btn').click(function(){

                var createInput=$("<input type='button'>");
                createInput.attr("id","close1");
                createInput.attr("value","close");
                $('#outer-div').append(createInput);
            });

            $("#close1").click(function(){
                alert('hi');
            });
        });


    </script>
</head>
<body>
    <div id='outer-div'>
        <input id='btn' type='button' value='click here'/>
    </div>

What's wrong with the code. I am not getting the alert when i click the dynamically generated button named as close. Please help it out

Community
  • 1
  • 1
Abhijit
  • 33
  • 1
  • 10
  • One of n number of questions that are related to this issue stackoverflow.com/questions/9484295/… – undefined 30 mins ago – Ram Oct 14 '12 at 14:21

1 Answers1

5

This would work :

    $(document).ready(function(){
        $('#btn').click(function(){

            var createInput=$("<input type='button'>");
            createInput.attr("id","close1");
            createInput.attr("value","close");
            $('#outer-div').append(createInput);
        });

        $(document).on('click', "#close1", function(){
            alert('hi');
        });
    });

The problem with

$("#close1").click...

is that it adds an event handler to nothing, as the collection is empty when you execute this line. The on function fixes that.

BTW, it's recommended to put your script at the end of the body instead of in the head.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758