-1

I am trying to perform action on id created in javaScript i.e. 'hh'. But nothing happens when i am clicking on the button. Please correct where i am going wrong.

    <script>
        $(document).ready(function () {

        $("button").click(function () {
            alert(this.id); // or alert($(this).attr('id'));
        });

        $(".hh").click(function () {
            alert("gggg");
        });
        $("#btn2").click(function () {
            $("ol").append("<li> <button id='hh'>Appended item</button></li>");
        });
    });
</script>


 <!DOCTYPE html>
    <html>
    <head>
        <script 
  src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    </head>
      <body>
        <ol>
        </ol>
           <button id="btn2">Append list item</button>
      </body>
    </html>

Thanks in advance.

Javed
  • 1,613
  • 17
  • 16
  • Also, the selector for `id="hh"` is `#hh`, although you probably do want to use a class instead since the intention seems to be to let users add multiple copies. – JJJ Sep 20 '17 at 12:26

1 Answers1

1

You have to use event delegation for elements which were added dynamically.

You should bind click event handler using .on() method.

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

Further more, you have to use id selector #. You append <button id='hh'>Appended item</button> which has id='hh', not class.

$(document).on("click","#hh",function () {
     alert("gggg");
});
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128