javascriptjquerybuttondynamicjquery-append

Not able to apply jquery to appended elements


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>

Solution

  • Use event delegation for attaching events to dynamically added element:

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