Toggle dynamically created divs

I am writing my own lightweight blogging platform (I'm trying to learn PHP and jQuery, so I just don't want to use Wordpress). Using PHP, I have a pagination system that displays 5 blog posts per page. In my while loop, I want to have a link that says “Leave a comment”, which when clicked will open a DIV that has a text box for entering a comment. The current code I'm using opens ALL 5 DIV comments on the page. I need to provide each of these DIVs with a unique identifier (based on the blog id I assume) and put it in the jquery toggle function so that only one DIV comment is opened when the link is clicked, and not in all of them. Can anyone help me please!

Here is my jQuery that opens ALL switched divs on the page:

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

And here is the code in my while loop that displays the blog post and 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 contents of the form in the commentBox div, I just need help with jQuery to make each of the 5 comment fields on the page unique, and they all switch individually, and not one to open all 5 DIV switches on the page, for example, that It is happening now. Any help that could be given to me would be greatly appreciated.

+5
source share
2 answers

Use the following jquery function:

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

http://api.jquery.com/next/

+2
source

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>

I hope you understand what I'm trying to say

+4
source

All Articles