toggle each div next to each link

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
infomamun
Forum Contributor
Posts: 102
Joined: Mon Dec 28, 2009 7:48 pm

toggle each div next to each link

Post by infomamun »

Hi there,
I have the following html element in my body section:
[text]<a class="tog" href="#">Click Me</a>
<div class="result">This is a container div</div>
<br /><a class="tog" href="#">Click Me</a>
<div class="result">This is a container div</div>[/text]
and the head section contain this:
[text]
.result{
display: none;
}
[/text]

What I want to do, while clicking on each link (<a>), next div will toggle and at the same time it will fetch data from another page into that div by post method. So my jquery code is:

Code: Select all

$(document).ready(function(){
 $(".tog").click(function(){
   if (!$(this).next(".result").data('loaded')){ 
   $.post("anotherpage.php",
   {id1:"value1"
   },function(data){
    $(this).next(".result").html(data);
    $(this).next(".result").data('loaded',true);
   });
    } 
 $(this).next(".result").slideToggle("slow");
 return false;
 });
});


each div next to each link (<a>) is toggling well by the above code. But the data is not fetching from another page. If I exclude $(this).next from each point of the above code like this:

Code: Select all

$(document).ready(function(){
 $(".tog").click(function(){
   if (!$(".result").data('loaded')){ 
   $.post("anotherpage.php",
   {id1:"value1"
   },function(data){
    $(".result").html(data);
    $(".result").data('loaded',true);
   });
    } 
 $(this).next(".result").slideToggle("slow");
 return false;
 });
});
each div is toggling after clicking each link and fetching post data from another page also, but clicking on any link is fetching data to all divs together at the same time.

My query is how can I revise the code, so that clicking on each link will toggle div next to that link and fetch data to next div only?
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: toggle each div next to each link

Post by pickle »

Your second code chunk does a global search on the page for all elements with the class "result", which is why all the divs get loaded.

My guess is there's a problem with the ajax call - maybe a bad url or malformed return content. Chrome dev tools and Firefox's Firebug both allow you to see AJAX requests on the console - check that out and I bet you'll see your problem.

Also, using .next() like that doesn't really need a selector. Might as well get rid of it and save yourself some milliseconds.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply