Find the nearest class using JavaScript

How can I display reply forms in the comment section based on the specific comment reply button that has been clicked? Currently, it shows forms for all comments instead of just one. This is the question.

What steps should I take to target the closest form and display only one at a time?

Code

// This button exists in all comments with the same class
<button type="button" class="btn btn-sm btn-primary text-light reply">Reply</button>

// Reply form DIV
<div class="blog-form mt-6 replyComment" style="display:none">// Form goes here</div>

// New comment form DIV
<div class="blog-form mt-6 originalComment"> // Form goes here </div>


$('.reply').click(function (e) {
  e.preventDefault();
  $('.replyComment').show();
  $('.originalComment').hide();
});

Update

Complete commenting code

<div class="blog-comments mt-4">
    @include('errors.errors')

    @if(isset($post))
        @forelse($post->comments as $comment)
            <div class="comments-1 w-100">
                <div class="comments-photo">
                    @if(!empty($comment->user->avatar))
                    <img class="img-profile rounded-circle" src="{{url('images/idus')}}/{{ $comment->user->avatar }}" alt="{{$comment->user->name}}">
                    @else
                    <img class="img-profile rounded-circle" src="{{asset('img/red_avatar.jpg')}}" alt="{{$comment->user->name}}">
                    @endif
                </div>
                <div class="comments-info">
                    <h6> {{$comment->user->name}} <span>{{$comment->created_at->format('M d, Y')}}</span></h6>
                    <div class="port-post-social float-right">
                        <button type="button" class="btn btn-sm btn-primary text-light reply">Reply</button>
                    </div>
                    <p class="mt-1">{!! $comment->comment !!}</p>
                </div>
            </div>

            <div class="blog-form mt-6 replyComment" style="display:none">
                <h4 class="mb-3">Post a Reply</h4>

                <form method="post" action="{{ route('reply.add') }}">
                    @csrf
                <div class="gray-form row">
                    <div class="col-md-12">
                        <input type="hidden" name="comment_id" value="{{ $comment->id }}" />
                        @if(isset($post))
                        <input type="hidden" name="post_id" value="{{ $post->id }}" />
                        @elseif(isset($product))
                        <input type="hidden" name="product_id" value="{{ $product->id }}" />
                        @endif
                    </div>
                    <div class="col-md-12">
                        <div class="form-group">
                            <textarea class="form-control" rows="7" name="comment" placeholder="Comment"></textarea>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <button class="button red" type="submit">SUBMIT</button>
                    </div>
                    <div>
                    </div>
                </div>
                </form>
            </div>

            @forelse($comment->replies as $reply)
            // Comments and replies structure...
            </div>
            @empty
            <h3>Be the first to leave a comment.</h3>
            @endforelse
        @empty
        <h3>No comments yet.</h3>
        @endforelse
    @else
    {{-- reserved for products reviews --}}
    @endif
</div>
<div class="blog-form mt-6 originalComment">
    <h4 class="mb-3">Post a Comment</h4>

    <form method="post" action="{{ route('comments.store') }}">
        @csrf
    <div class="gray-form row">
        <div class="col-md-12">
            @if(isset($post))
            <input type="hidden" name="post_id" value="{{ $post->id }}" />
            @elseif(isset($product))
            <input type="hidden" name="product_id" value="{{ $product->id }}" />
            @endif
        </div>
        <div class="col-md-12">
            <div class="form-group">
                <textarea class="form-control" rows="7" name="comment" placeholder="Comment"></textarea>
            </div>
        </div>
        <div class="col-md-12">
            <button class="button red" type="submit">SUBMIT</button>
        </div>
        <div>
        </div>
    </div>
    </form>
</div>

Condensed forms above for easier comprehension

Structure

<comments>
  -reply button
  <reply form></reply form>

  <comment reply>
       -reply button
       <reply form></reply form>


       <comment reply replies>
       <comment reply replies>
   </comment reply>

</comments>

<comment form>
</comment form>

Answer №1

If you're looking to display a specific <div> element that comes after the button's parent element with the class comments-1, here's how you can achieve it:

To target the parent, you can use .closest('.comments-1'), and to select the following element, you can use .next('.replyComment').

$('.reply').click(function (e) {
  e.preventDefault();
  $(".replyComment, .originalComment").hide();
  $(this).closest('.comments-1').next('.replyComment').show();
});

Answer №2

If there is a form above the button, the function will not work as expected:

function toggleForm(arg) {
var forms = document.getElementsByClassName("blog-form");
forms[arg].style.display = "block";
for(var i = 1; i < forms.length; i++) {
    if(i != arg) {
    forms[i].style.display = "none";
    }      
}
}
<button onclick = "toggleForm(0)">Reply</button>
<form class = "blog-form" style = "display: none">
<input>
</form>
<form class = "blog-form" style = "display: none">

<input>
</form>
<button onclick = "toggleForm(1)">Another Reply</button>

To make this function work effectively, I am manipulating the CSS display property.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing a Popover Notification When Clicked

I'm a beginner at this. I came across an example of a popover message box in the link provided below. I attempted to implement it, but for some reason, it's not working. Could I be overlooking something? Alternatively, is there a simpler way to ...

Simple way to retrieve the first and last date of the current month using Node.js

I need help with retrieving the first and last date of the current month using the code below:- let currentDate = new Date(); let month = currentDate.getMonth() + 1; console.log(month); let firstDate = new Date(currentDate.getFullYear(), currentDate.getMon ...

Error message: The Slick Carousal encountered an unexpected problem - TypeError:undefined is not a function

I'm having an issue with a script for a Slick Carousel inside of some Ajax Tabs. I keep encountering the Uncaught TypeError: undefined is not a function error, but I'm unsure what exactly it's pointing to. $(document).ready(function(){ ...

Introducing a variety of services into the system

From my understanding, services must be provided and injected, meaning each service needs to be placed inside the constructor like this: constructor (private a: AService, private B: BService) {} In my scenario, I have multiple services that all follow th ...

Only the homepage experiences issues with the Bootstrap 4 mobile navigation menu failing to remain open

http://example.com/index.html I am in the process of building my first website using Bootstrap 4 beta. I have encountered an issue with the mobile navigation menu specifically on the HOME PAGE. When clicking the hamburger icon, the nav menu opens briefly ...

Using Three.js to turn an object around its Y-axis to face a specific direction

After pondering over it for a week, I realized that the concept is too complex for me to grasp. The issue I am facing is when I click on specific coordinates on the plane, I want my 3D model to rotate towards those coordinates and then move to match them ( ...

Adding an item to a nested array within an object in a Redux reducer

Here is an example of my initial state: let initialState = { data: { name: 'john', books: [ { name: 'a', price: 220 } ] } } Is there ...

JS code function experiences issues while being utilized within another JS function

I have encountered an issue with getting a value that I calculated within a span tag in my repeating form. The value is successfully retrieved in my regular form, but when I add another row, it no longer works. The code functions correctly with the first ...

The replacement of className in inline SVG is not permitted (Error: 'Cannot read property 'className.replace' of undefined')

I've hit a roadblock trying to manipulate classes within an SVG document to modify the rect elements. The code works smoothly on divs in an external document, but I've tried several other solutions as well – all listed below. I'm still rel ...

The text-center alignment in Bootstrap doesn't seem to be applying to buttons

After spending a considerable amount of time trying to center two buttons in Bootstrap, I came across the "text-center" class offered by Bootstrap. However, no matter where I include this class, it doesn't seem to have any effect on the alignment of t ...

Navigate back to the previous route within the Vue router hierarchy

In my Vue application, I have a Settings page with child routes such as settings/user, settings/addUser, etc. I am looking to implement a back button that when pressed, takes the user back to the specific page they visited within the Settings section. Usin ...

Updating the selected value of a dropdown in Angular using the patch method

I am currently working on an "Edit View" feature for my application. The information is fetched from an API call and then I use patch to populate the form with these values. However, I am encountering a problem with the dropdown select as the default value ...

React JavaScript application encountered an error: Uncaught SyntaxError due to an unexpected token '<'

My program encountered a syntax error at line <div>Hello World!</div> This is the code that is causing the error <!DOCTYPE html> <html> <head> <script src="libs/react.min.js"></script> <script src="lib ...

What is the best way to connect my products on an ecommerce site with hundreds of images?

Despite thoroughly searching the internet, I have been unable to find a solution to my dilemma. I am creating a platform that showcases a lengthy list of products on the website. Additionally, I have a database of pictures stored locally that need to be ...

Converting JSON data into an array containing individual objects, and inserting a new item into each object

I've been working on retrieving data from a JSON file and successfully creating an array of objects. However, I am trying to add an item to each object in the array simultaneously. Check out my current code: var linklist = []; $.getJSON('links. ...

Tips for updating the value of an Array of Objects using an array containing the desired string value

I have a scenario where I need to update the 'checked' key value to true for objects in an array based on another array's values. var daysActive = ['monday', 'tuesday', 'wednesday']; var weekDays = [{ "name": ...

Enhance the efficiency of DataTable by optimizing cell class modifications

I have been very pleased with the performance of jquery DataTables, but I have encountered a situation where I need to optimize it further. Specifically, I am updating the class of a cell based on its data. Currently, I am achieving this by using the ren ...

"Encountering a hiccup in executing map.reduce

var mapFunction1 = function() { for (var i = 0; i < this.money.length; i++) { emit("balance", this.money[i].amount); } }; var reduceFunction1 = function(keyBalance, valuesBalance) { return Array.sum(valuesBalance); }; db.users.ma ...

React-Bootstrap's defaultActiveKey in Tabs component does not update with state changes

<Tabs> is not updating defaultActiveKey when the State changes. I had to initially open the "write" tab for one scenario And then automatically switch to the "read" tab for another scenario This is how my code looks: this.state = { defaultTab: "wr ...

Discover the step-by-step guide to creating a dynamic and adaptable gallery layout using

I have encountered an issue with my gallery where the images stack once the window is resized. Is there a way to ensure that the layout remains consistent across all screen sizes? <div class="container"> <div class="gallery"> &l ...