Ans: Use $(document).on("click",".dosomething",function(){}) insted $(".dosomething").click(function(){})
Follwoing example demonstrate how to add event to dynamically created elements.

<!-- 
Used basic html and bootstrap skeleton from the below link for style purpose which contains bootstrap.css,bootstrap.js,jquery.js 
https://www.w3schools.com/bootstrap/bootstrap_get_started.asp 
-->
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Click event is not working on dynamically created elements in Jquery?</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">        
    </head>
    <body>
        <div class="container" style="max-width:800px;margin:0 auto;margin-top:50px;">  
            <div>
                <h2 style="margin-bottom:50px;">Live Demo: Click event is not working on dynamically created elements in Jquery?</h2>              
            </div>
            <div>
                <button type="button" class="add-btn btn btn-success">Add Button Dynamic</button>   
            </div>
            <div style="margin-top:20px;" class="append-btn-wrap"></div>
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <script>
            $(document).ready(function () {
                $(".add-btn").click(function () {
                    $(".append-btn-wrap").append('<button class="btn btn-warning dosomething">I am Dynamic Button. Click Me</button>');
                });
            });
            $(document).on("click", ".dosomething", function () {
                alert("I am working dude");
            });
        </script>
    </body>
</html>
Written by
Check out this Author's contributed articles.
If you like Tutorialsmint and would like to contribute, you can also write an article using Write an Article. See your article appearing on the Tutorialsmint main page and help other programmers to enhance their knowledge.

Comments(0)

RECENT TUTORIALS
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Wed Dec 26 • 08:00 AM GMT
Edit Post
Add Reply