简体   繁体   中英

Close all forms with a button in Django

I building a threaded comment system (Reddit-like) in Django 3.0
A comment can have as many replies as possible. For each comment made, a Reply form is shown below it. Now, if I don't hide the forms, the page looks very bad, cluttered with textareas.

I need the following: A 'Reply' button, clicking which the reply form can be displayed/hidden.

Here's what I have tried:

  1. Added a class .replyForm to the forms.
    Added a class .hideBtn to the hide Buttons.
    Used JQuery:
  $(".hideBtn").click(function(){
        $(".replyForm").toggle();
    });

Now, this works fine, but clicking a reply button opens up all the forms at the same time.
This is expected as the class belonging to each form is the same.

  1. Using Django's template tags I managed to make the id of each form and button unique.
    Example: id = "replyForm{{comment.id}}" which renders as replyForm123 if comment.id = 123
    But I am not able to use this in any productive way.
    I can't access the id outside the for loop (which displays the comments).
    I tried adding the JQuery script inside the loop, and created 2 variable, one for the id for the button, and other for the form's id.
    But as the loop executes, the variables change accordingly, and finally they store the id's of the last comment only, rendering all the other toggle buttons useless.

I feel that I am complicating things way too much, I am very new to JS and JQuery, and I'am only using them because I couldn't find a pythonic/django-based way for doing this.

Is there a simpler, more elegant way for doing this? Any help is appreciated

Edit 1:
I have found a very simple solution using Bootstrap 4's collapse class , but still want to know the JQuery way of doing this.

Try this:

$(".replyForm").click(function(){
    $(this).toggle();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM