why my upvote button only works for the first post?

I follow the instruction in tangowithdjango to add a 'like' button into my forum app.

the html file and javascript:

<script>
$(document).ready(function(){
  $("#upvote").click(function(){
    var postid;
    postid = $(this).attr("data-r-id");
    $.get('/upvote/', {post_id: postid}, function(data){
               $('#like_count').html(data);
              
    });
  });
});
</script>
<a id="upvote" data-r-id="{{r.id}}" class="label-info label pull-right">?<div id="like_count">{{r.upvotes}}</div></a>

views.py

def upvote(request):
    post_id = None
    if request.method == 'GET':
        post_id = request.GET['post_id']
    votes = 0
    if post_id:
        p = post.objects.get(id=post_id)
        if p :
            votes = p.upvotes + 1
            p.upvotes = votes
            p.save()
    return HttpResponse(votes)

urls.py

urlpatterns = patterns(
    url(r'^upvote/$', 'upvote', name='upvote'),
)

when click the #upvote button ,the #like_count increase by one . However , it works just for the first post. If I click the rest of posts , I get no response at all.

Answers 1

  • I suggest you to give upvote as class not as id because id refers an unique element in your document.

    $(document).ready(function(){
      $(".upvote").click(function(){
        var postid;
        postid = $(this).attr("data-r-id");
        $.get('/upvote/', {post_id: postid}, function(data){
                   $('#like-count-' + postid).html(data);
    
        });
      });
    });
    

    and your html should look like,

    <a data-r-id="{{r.id}}" class="label-info label pull-right upvote">?<div id="like-count-{{r.id}}">{{r.upvotes}}</div></a>
    

Related Articles