Reputation: 59
I am trying to make a comment system using ajax.
HTML snippet :
<div class="ThreadComments">
<div class="ActualComments">
<div class="row collapse">
<div class="large-1 columns small-3" align="center">
<img src="http://placehold.it/35x35&text=[img]" />
</div>
<div class="large-11 columns">
<p class="speechBubbleSecondary"><strong class="commenter_name">George</strong>Comment text <span class="MRWlabel" MRW-data="">Img</span>
</p>
</div>
</div>
</div>
<div class="row collapse">
<div class="large-1 columns small-3" align="center">
<img src="http://placehold.it/35x35&text=[img]" />
</div>
<div class="large-11 columns">
<textarea class="WP_commentator" style="resize: none; height: 35px; font-size: 12px; padding: 2px;" pi-data="<?= $post['post_id'] ?>"></textarea>
</div>
</div>
</div>
I am using Foundation 5 thus the heavy mark-up , and I want when an user posts a comment to append it to the ActualComments
div , the problem is I can't manage to select it , because there are more posts with the same mark-up.
This is my ajax function :
$('textarea.WP_commentator').focus(function () {
$('textarea.WP_commentator').keydown(function (keycheckcode) {
if (keycheckcode.keyCode == 13) {
var commentText = $(this).val();
var postId = $(this).attr('pi-data');
$.ajax({
type: "post",
url: "commentator",
data: {
comment: commentText,
post_id: postId
},
success: function (html) {
$('textarea.WP_commentator').val("");
append(html);
}
});
}
});
});
Upvotes: 0
Views: 52
Reputation: 61063
First, I think your focus function is redundant. You need to establish which element text is being entered into, and use that for relative DOM traversal. Something like this:
$('textarea.WP_commentator').keydown(function (keycheckcode) {
var myElem = $(this);
if (keycheckcode.keyCode == 13) {
...
$.ajax({
...
success: function (html) {
myElem.closest('.ActualCommentsSibling')
.siblings('.ActualComments').append(html);
}
});
}
});
I added a sibling element in there because .ActualComments
isn't an ancestor element of myElem
. You'd need to add an appropriate class to that element in your HTML.
Upvotes: 1
Reputation: 33870
You can cache you variable and then use some DOM navigation method.
var $this = $(this);
var commentText = $this.val();
var postId = $this.attr('pi-data');
$.ajax({
type: "post",
url: "commentator",
data: {comment: commentText, post_id: postId},
success: function(html) {
$this.val("")
.closest('.ThreadComments').find('.ActualComments').append(html);
}
});
Upvotes: 2