Raman Raman - 1 month ago 6
jQuery Question

jquery event not working for dynamic elements

on click of button i am adding dynamic element eg: anchor tag having some id,
on clicking the dynamic element alert should open which is not happening.

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

$("#submit").on("click",function(){
$("#op").html("<a href='javascript:void(0)' id='demo'>Click</a>");
});
$("#demo").on("click",function(){
alert('In Demo....');
});
});

</script>
</head>
<body>
<button id="submit">Submit</button>
<pre id='op' ></pre>
</body>
</html>

Answer

Try this

$(document).on("click","#submit",function(){
     $("#op").html("<a href='javascript:void(0)' id='demo'>Click</a>");
});

$(document).on("click","#demo",function(){
    alert('In Demo....');
});

The problem is that your events are not attached to the element.

Comments