Estoy tratando de agregar comentarios de respuesta a mi sistema de comentarios en un proyecto Laravel 8. He escrito un script para mostrar el formulario de respuesta cuando se hace clic en el botón de respuesta, pero el formulario siempre se muestra de forma predeterminada. Sin embargo, cuando se hace clic en el botón de respuesta, el formulario se oculta y se muestra en el segundo clic. Parece que no entiendo lo que no estoy haciendo bien. Por favor, necesito su asistente en este sentido. Este es mi código:
//The form <div class="card-body"> @if ($PostDetails->comment) @foreach($PostDetails->comment as $comment) <blockquote class="blockquote"> <p class="mb-0">{{ $comment->comment }}</p> <footer class="blockquote-footer">{{ $comment->user->name }}</footer> </blockquote> {{-- Reply Comment Section --}} <button id="reply-button" onclick="showReplyForm('{{$comment->id}}', '{{ $comment->user->name }}')" class="border-0 bg-transparent">Reply</button> <div class="row flex-row d-flex"> <form action="" method="post"> <div class="col-lg-12"> <textarea id="reply-form-{{$comment->id}}" cols="80" rows="2" class="form-control mb-10" name="replyMessage"></textarea> </div> </form> </div> <hr> @endforeach @endif </div> //The script is: <script type="text/javascript"> function showReplyForm(commentId){ var x = document.getElementById(`reply-form-${commentId}`); if (x.style.display === "none") { x.style.display = "block"; }else{ x.style.display = "none"; } } </script>Agregue el style="display:none;" para que quede oculto al principio.
<div class="card-body"> @if ($PostDetails->comment) @foreach($PostDetails->comment as $comment) <blockquote class="blockquote"> <p class="mb-0">{{ $comment->comment }}</p> <footer class="blockquote-footer">{{ $comment->user->name }}</footer> </blockquote> {{-- Reply Comment Section --}} <button id="reply-button" onclick="showReplyForm('{{$comment->id}}', '{{ $comment->user->name }}')" class="border-0 bg-transparent">Reply</button> <div class="row flex-row d-flex" style="display:none"> <form action="" method="post"> <div class="col-lg-12"> <textarea id="reply-form-{{$comment->id}}" cols="80" rows="2" class="form-control mb-10" name="replyMessage"></textarea> </div> </form> </div> <hr> @endforeach @endif </div> //The script is: <script type="text/javascript"> function showReplyForm(commentId){ var x = document.getElementById(`reply-form-${commentId}`); if (x.style.display === "none") { x.style.display = "block"; }else{ x.style.display = "none"; } } </script>Cambie el atributo id de sus botones a class="reply-button" y agregue style="display:none" a sus textareas de texto. Luego puede simplificar su parte de JavaScript para
document.querySelectorAll(".reply-button").forEach(btn=>btn.onclick=ev=>{ const x=ev.target.nextElementSibling.querySelector("textarea"); x.style.display = x.style.display ==="none"?"":"none"; }); Entonces ya no hay necesidad de asignar id s a las áreas de texto individuales.