bharathi
bharathi

Reputation: 6271

Anchor tag with jquery not working

Calling a jquery with dynamically generated anchor tag is not working. Whereas the same with hard coded anchor tag the jquery is working fine.

Code:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">      </script>
    <script>
    $(document).ready(function(){

        var value = "HI!!!";
        $("button").click(function(){
            $("#box").html("<a class='dynamic' href='#' dataid='"+value +"'>Generate</a>");
        });
        $(".hardcode").click(function () {
            alert("Calling function");
        });
        $(".dynamic").click(function () {
            alert("ggsss function");
        });

    });
    </script>
</head>
<body>
    <a class="hardcode" href="#" dataid="sss">Generate</a>
    <button>Change content of all p elements</button>

    <div id="box">
    </div>
</body>
</html>

Upvotes: 0

Views: 2021

Answers (2)

palaѕн
palaѕн

Reputation: 73886

Since the dynamic anchor tag class is added dynamically, you will need to use event delegation to register the event handler like:

// New way (jQuery 1.7+) - .on(events, selector, handler)
$('#box').on('click', '.dynamic', function(event) {
    event.preventDefault();
    alert("ggsss function"); 
});

This will attach your event to any anchors within the #box element, reducing the scope of having to check the whole document element tree and increasing efficiency.

Fiddle Demo

More Info:

Upvotes: 1

Jayesh Chitroda
Jayesh Chitroda

Reputation: 5049

Use $(document).on("click") for dynamically generated element

var value = "HI!!!";
$("button").click(function(){
    $("#box").html("<a class='dynamic' href='#' dataid='"+value +"'>Generate</a>");
});
$(document).on("click",".hardcode",function () {
 alert("Calling function");
});
$(document).on("click",".dynamic",function () {
 alert("ggsss function");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 <a class="hardcode" href="#" dataid="sss">Generate</a>
     <button>Change content of all p elements</button>

     <div id="box">
     </div>

Upvotes: 0

Related Questions