P murad P murad - 6 months ago 17
Javascript Question

Same jquery for different elements with same class name

I have got this HTML that i get from PHP while loop

<div class="WriteCom <?php echo $Class?>">
<form class="c_comment " method="post"><input type="text" class="Comment_In" ></form></div>
</div>


And this Jquery

var commentcount=0;
$(".WriteCom").children().submit(function() {
var numItems = $(this).parent().siblings('.F_W_comments').children('.CommentsAw').length;
var cc=$(this).children().val();
var i=$(this).parent().siblings(".c_jq").children().attr("data-i");
var com=$(this);
commentcount++;
$(this).children().val('');
$.ajax({
type: "GET",
url: '../connect.php',
data: "C=" + cc+"&I="+i,
success:function(data) {
var json_x = $.parseJSON(data);
com.parent().parent().siblings('.c_jq').children(".Comments").children(".L_CS").html(json_x[0]);
if (numItems>=4) {
com.parent().siblings('.F_W_comments').children('.CommentsAw:first').remove();
}
com.parent().siblings('.F_W_comments').append('<div class="cn_'+commentcount+' CommentsAw Comment_HsJ"><img src="../users/'+json_x[3]+'"><span>'+json_x[2]+'</span><span class="s2">'+json_x[1]+'</span></div>');
if (commentcount==1) {
$(".Comment_Hs:first").css("marginTop","-75px");
$(".cn_1").css("marginBottom","15px");
}else if (commentcount==2) {
$(".Comment_Hs:first").css("marginTop","-90px");
$(".cn_1").css("marginBottom","0px");
$(".cn_2").css("marginBottom","15px");
$(".cn_2").css("marginTop","-10px");
}else if (commentcount==3) {
$(".Comment_Hs:first").css("marginTop","-105px");
$(".cn_3").css("marginTop","-10px");
$(".cn_3").css("marginBottom","15px");
$(".cn_2").css("marginBottom","0px");
}else if (commentcount==4) {
$(".Comment_HsJ:first").css("marginTop","-105px");
$(".cn_4").css("marginTop","-10px");
$(".cn_4").css("marginBottom","15px");
$(".cn_3").css("marginBottom","0px");
}else{
$(".Comment_HsJ:first").css("marginTop","-105px");
$(".Comment_HsJ:eq(3)").css("marginTop","-10px");
$(".Comment_HsJ:eq(3)").css("marginBottom","15px");
$(".Comment_HsJ:eq(2)").css("marginBottom","0px");
}
}
});
return false;
});


So when i have several posts and i comment on first post
commentcount
becomes 1 and when i comment on second post
commentcount
becomes 2.But i want to have commentcount for each uploaded file individually.

Answer

Put the comment count in the DIV for the post.

$(".WriteCom").children().submit(function() {
    var commentcount = $(this).parent().data("commentcount") || 0;
    commentcount++;
    $(this).parent().data("commentcount", commentcount);
    // rest of code
});
Comments