Vincent
Vincent

Reputation: 3

Thymeleaf foreach loop with button event inside

I have used the Thymeleaf foreach to traverse all posts where each post has a "Comment" button. I would like to display the comment list after click this "Comment" button.

The default is hidden

The following is my codes:

            <div th:each="post:${posts}">
                <div class="panel panel-default" th:object="${post}">
                    <div class="panel-body">
                        <p th:text="*{user.username}">username</p>
                        <p th:text="*{createTime}">time</p>
                        <p th:text="*{content}">content</p>
                        <div>
                            <form th:action="@{/posts/liked/input}" method="post"
                                style="display: inline">
                                <input type="hidden" name="postId" id="postIdId"
                                    class="form-control" th:value="*{id}">
                                <button type="submit" class="btn btn-primary">like</button>
                            </form>
                            <button class="btn btn-primary commentBt"
                                style="display: inline">Comment</button>
                        </div>
                    </div>

                    <!--  This is the part I want to show after click Comment -->
                    <div style="display: none">
                        <form th:action="@{/posts/comment/input}" method="post">
                            <textarea class="form-control" name="content" id="contentId"
                                rows="1"></textarea>
                            <input type="hidden" name="postId" id="postIdId"
                                class="form-control" th:value="*{id}">
                            <button type="submit" class="btn btn-primary">Reply</button>
                        </form>
                        <div th:each="comment:*{comments}">
                            <div th:object="${comment}">
                                <p th:text="*{content}">content</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

How to do this in the foreach loop?

Upvotes: 0

Views: 1735

Answers (1)

Kevinsss
Kevinsss

Reputation: 814

You can do this by using js, below are example codes.

First, you need to add onclick to commit button:

<button  class="btn btn-primary commentBt"
                            style="display: inline" onclick="showDiv()">Comment</button>

Then, get the hidden div and edit function showDiv to dispaly the div.

  <!-- set id -->
  <div id="test" style="display: none">

    <script>
    <!-- function to change display to block -->
    function showDiv(){
        var div = document.getElementById("test");
        div.style.display="block";
    }
</script>

Hope this will help you!

Upvotes: 1

Related Questions