Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle dynamically created divs

I'm writing my own lightweight blogging platform (I'm trying to learn PHP & jQuery so I don't just want to use Wordpress). Using PHP, I have a pagination system that shows 5 blog posts per page. Within my while loop, I want to have a link that says "Leave a Comment" which, when clicked, will open up a DIV that has a textbox to input a comment. The current code i'm using opens up ALL 5 comment DIVs on the page. I need to be able to give each of those commment DIV's a unique ID (based on the blog post's ID I assume) and put that in my jquery toggle function so that only one comment DIV is opened when the link is clicked, not all of them. Can anyone please help me?

Here's my jQuery which opens up ALL toggled divs on the page:

<script type="text/javascript"> 
   $(document).ready(function() {  
     $(".toggleCommentBox").click(function() {
       $(".commentBox").toggle()
     });  
   });      
</script>

And here's the code in my while loop which displays the blog post and the link:

<a href = "#" class = "toggleCommentBox">Leave a Comment</a>

<div class = "commentBox" style = "display:none;">
    ...Form stuff in here
</div>

I don't need help with the form stuff within the commentBox div, I just need help with the jQuery to make each of the 5 comment boxes on the page unique, and all of them toggle-able individually, instead of one link opening all 5 toggle DIVs on the page, like what happens now. Any help anyone could give me would be greatly appreciated.

like image 837
John Avatar asked Mar 22 '13 05:03

John


Video Answer


1 Answers

Try something like this

<script type="text/javascript"> 
 $(document).ready(function() {  
 $(".toggleCommentBox").each(function{

   var getId = $(this).attr('getId');
   $(this).click(function(){

        $("#commentBox"+getId).toggle();
     })
  })
});      

<a href = "#" class = "toggleCommentBox" getId='1' >Leave a Comment</a>

<div class = "commentBox" style = "display:none;" id="commentBox1">
...Form stuff in here
</div>

Hope you understand what I am trying to say

like image 168
alwaysLearn Avatar answered Oct 28 '22 16:10

alwaysLearn