Shubham Jha Shubham Jha - 1 month ago 14
Javascript Question

jQuery on click fade in hidden element in while loop

I have a form in while loop which activates when I click on

Reply
button. This I can do simply but its in while loop and requires a unique ID. With my code its working till now but it works only for the first result. When I click on the other results nothing happens. Even though I have already assigned a unique ID its not working. My code is given below:

jQuery part:

$(document).ready(function() {
$("#reply").on('click', 'a.click', function() {
var rowid = $(this).attr("data-rowid");
$(".reply-comment-holder[data-rowid='" + rowid + "']").fadeToggle(800),
$(this).toggleClass(".reply-comment-holder[data-rowid='" + rowid + "']");
});
});


PHP HTML part:

<?php while($fetch_cmts = $get_cmtq->fetch()){ extract($fetch_cmts); ?>
<div id="reply"><a href="javascript:;" data-rowid="<?php echo $cmt_id?>" class="click show-reply-box">Reply</a></div>
<div class="reply-comment-holder" data-rowid="<?php echo $cmt_id?>" style="display:none;">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="full-width cmtform" id="cmt_form_id_<?php echo $cmt_id?>">
<input type="hidden" name="status_id" value="<?php echo $cmt_id; ?>" id="cmtsid_<?php echo $cmt_id?>" />
<textarea name="comment" placeholder="Give a reply..." class="reply-comment-field commentarea" id="replycomment_<?php echo $cmt_id?>"></textarea>
</form>
</div>
<?php } ?>


Please help with jQuery/Ajax.

Answer

HTML

<div class="reply"><a href="javascript:;" data-rowid="1" class="click show-reply-box">Reply</a></div>
<div class="reply-comment-holder" data-rowid="1" style="display:none;">
          <form method="post" action="#" class="full-width cmtform" id="cmt_form_id_1">
            <input type="hidden" name="status_id" value="1" id="cmtsid_1" />
            <textarea name="comment" placeholder="Give a reply..." class="reply-comment-field commentarea" id="replycomment_1"></textarea>
          </form>
        </div>
<div class="reply"><a href="javascript:;" data-rowid="2" class="click show-reply-box">Reply</a></div>
<div class="reply-comment-holder" data-rowid="2" style="display:none;">
          <form method="post" action="#" class="full-width cmtform" id="cmt_form_id_2">
            <input type="hidden" name="status_id" value="2" id="cmtsid_2" />
            <textarea name="comment" placeholder="Give a reply..." class="reply-comment-field commentarea" id="replycomment_2"></textarea>
          </form>
        </div>  

javascript

$(document).ready(function() {
    $(".reply").on('click', 'a.click', function() {
        var rowid = $(this).attr("data-rowid");
        $(".reply-comment-holder[data-rowid='" + rowid + "']").fadeToggle(800),
        $(this).toggleClass(".reply-comment-holder[data-rowid='" + rowid + "']");
    });
});

jsbin is listed in comments above.

Comments