-1

I am adding #show_data button dynamically, but not able to use jQuery on that button. Hi! data is never logged How do I add Scripts to dynamic elements?

<body>

    <button id="show_fields">Show Fields</button>
    <div id="button"></div>

    <script>

        $("#show_fields").click(function(){
            console.log('Hi! fields');
            $("#button").html("<button id=\"show_data\">Show data</button>");
        });

        $("#show_data").click(function(){
            console.log('Hi! data');
        });

    </script>

</body>
Swaraj Giri
  • 3,801
  • 2
  • 20
  • 36

1 Answers1

1

Use event delegation for attaching events to dynamically added element:

$("#button").on('click','#show_data',function(){
   console.log('Hi! data');
});
Milind Anantwar
  • 77,788
  • 22
  • 86
  • 114