nabil menzel
nabil menzel

Reputation: 3

Unable to use created element with jquery

I'm new in jquery and I suffer from a problem which is a little strange. After creating a div in jquery,I can't use it,this example will show you how is the problem! let's assume that in the get.php page there is just:echo "test test"; the code in my file :

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
  $("#bda").click(function()
{
$.post("get.php",function(data){
$("#tdiv").append('<div class="info" >'+data +'</div>');
});     
});

$(".info").click(function()
{
  alert("done");
});
});
</script>     
</head>

<body>
 <div id="bda">click here</div>
 <div align="center" style="border:1px solid blue" id="tdiv">    
  example
 </div>
<div class="info" >it works here</div>

Can some one help me..

Upvotes: 0

Views: 168

Answers (3)

Florian Brinker
Florian Brinker

Reputation: 735

you bind the click event to info classes at the execution of the script but you add the new div later during the ajax process. you have to reassign the click event to this class

try not binding with .click(), use .on() instead, like mentioned here: http://api.jquery.com/on/

$("body").on('click', '.info', function() {
  alert("done");
});

Upvotes: 0

pimvdb
pimvdb

Reputation: 154828

What jQuery does with $(".info") is selecting the .info elements at the time you call it - which is only one element since the other one is appended later (through ajax). That other element therefore has no click event attached. So, the .info selector is not actually saved - merely the elements are pulled out of the document and then the selector is discarded.

What you want is that jQuery checks element against a selector when you click. You can do that with event delegation:

// When you click somewhere in the body, jQuery will check whether you
// clicked on a `.info` element and execute the function in that case.
// This also works for elements added later on.

$("body").on("click", ".info", function() { ... });

Upvotes: 2

Ram
Ram

Reputation: 144689

as you insert new element to the DOM, you should delegate the event:

$("body").on('click', '.info', function() {
  alert("done");
});

Upvotes: 1

Related Questions