SomeBeginner
SomeBeginner

Reputation: 49

Creating textarea and multiple elements on click for replying to a comment

Currently, I have a PHP script that fetches comments from database (com_text, name, etc) and I echo them and for each result, I also echoing a div with a hidden textarea (from CSS) and multiple input fields (type='hidden'), then on a button click (reply) I change the div with the textarea from hidden to in-line so the user can type and reply to a comment. Ex:

foreach($result as $r){
<div class='comments'>
echo"<p>$r['com_text']</p>";
<button> reply <button>
etc
</div>

<div class="reply_container>
<form>
<textarea></textarea>
<input type="hidden value="value_from_database" name="">
<input type="hidden value="" name="">
<button type="submit></button>
</form>
</div>
}

You get the idea for each comment I also create a hidden textarea to let people reply.

My question is: can I do something like this dynamically so I don't have to create this for every comment? Or is there a better way?

The idea that I have is to create another PHP script that appends something like this with Ajax, is that the way to go?

Thank you.

Upvotes: 0

Views: 331

Answers (1)

Snowmonkey
Snowmonkey

Reputation: 3761

So I have a single reply div, and multiple comments. Clicking on any .comment div will trigger my listener, which will populate the relevant fields in the reply div and show it. Is this something like you're looking for?

$(".comments-pane").on("click", ".comment", function(){
  var el = $(this);
  var elID = $(this).attr("id");
  var elText = $(this).text();
  
  $(".reply_container")
     .find("h3")
       .text("Your reply to "+elText).end()
     .find(".comment_id")
       .val(elID).end()
     .show();
   });
.reply_container {
  display: none;
}
.comment {
  border-bottom: 1px solid #999;
  padding: 5px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="comments-pane">
  <div class="comment" id="4042311">
    The first one
  </div>
  <div class="comment" id="4042313">
    A follow-up comment
  </div>
  <div class="comment" id="4042317">
    Yet a third comment.
  </div>
</div>
  
  
<div class="reply_container">
  <h3></h3>
<form>
<input type="hidden" name="comment_id">
<input type="text" value="" name="reply_text">
<button type="submit">Reply</button>
</form>
</div>

Upvotes: 1

Related Questions