ofey ofey - 6 months ago 11
jQuery Question

Dynamically assigning ID to an element with jQuery

I have a table cell with a dynamically assigned id like this,

<tbody>
{% for item in thread_model %}
<tr>
.....
<td id="{{ item.id }}" class='btn vote_up'>{{ item.id }} Vote Up</td>
<td id="{{ item.id }}" class='btn vote_down'>{{ item.id }} Vote Down</td>
<td id="voted{{ item.id }}">{{ item.vote }}</td>
........
</tr>
{% endfor %}
</tbody>


This works fine and then I have a bit of ajax which calls a Django view. But then I wish to set the innerHTML of that cell. But how do I get the jQuery to put the innerHTML into the table cell with the same id as the row of the vote up or down which I pressed?

$(document).ready(function() {
$('.vote_up').on('click', function() {
$.get("/vote_up/" + this.id + "/", function(data) {
$('#voted' + this.id).innerHTML = data;
});
});
$('.vote_down').on('click', function() {
$.get("/vote_down/" + this.id + "/", function(data) {
$('#voted' + this.id).innerHTML = data;
});
});
});


The urls,

url(r'^vote_up/(?P<id>\d+)/$', home.vote_up, name='vote_up'),
url(r'^vote_down/(?P<id>\d+)/$', home.vote_down, name='vote_down'),


The views look like this,

def vote_up(request, id):
posts = PostModel.objects.get(pk = id)
posts.vote += 1
PostModel.objects.filter(pk=id).update(vote=posts.vote)
return HttpResponse(posts.vote, content_type="text/plain")

def vote_down(request, id):
posts = PostModel.objects.get(pk = id)
posts.vote -= 1
PostModel.objects.filter(pk=id).update(vote=posts.vote)
return HttpResponse(posts.vote, content_type="text/plain")


Thanks

Answer

this.id is undefind inside $.get. SO you should change your code like this

$(document).ready(function() {
      $('.vote_up').on('click', function() {
        var id = this.id;
        $.get("/vote_up/" + id + "/", function(data) {
          $('#voted' + id).html(data);
        });
      });
      $('.vote_down').on('click', function() {
        var id = this.id;
        $.get("/vote_down/" + id + "/", function(data) {
          $('#voted' + id).html(data);
        });
      });
    });